Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- public:
- vector<vector<int>> verticalTraversal(TreeNode* root) {
- multiset<tuple<int, int, int>> order;
- queue<tuple<TreeNode*, int, int>> q;
- q.emplace(root, 0, 0);
- while (!q.empty()) {
- auto [node, row, col] = q.front();
- q.pop();
- order.emplace(col, row, node->val);
- if (node->left != nullptr) {
- q.emplace(node->left, row + 1, col - 1);
- }
- if (node->right != nullptr) {
- q.emplace(node->right, row + 1, col + 1);
- }
- }
- int last = INT_MIN;
- vector<int> curr;
- vector<vector<int>> ans;
- for (auto [col, row, v]: order) {
- if (col > last) {
- if (!curr.empty()) {
- ans.push_back(curr);
- }
- last = col;
- curr.clear();
- }
- curr.push_back(v);
- }
- if (!curr.empty()) {
- ans.push_back(curr);
- }
- return ans;
- }
- };
Advertisement
RAW Paste Data
Copied
Advertisement