314. Binary Tree Vertical Order Traversal
Given the root of a binary tree, return the vertical order traversal of its nodes’ values. (i.e., from top to bottom, column by column).
If two nodes are in the same row and column, the order should be from left to right.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
class Solution { map<int, multimap<int, int>> m; void build(TreeNode* node, int order = 0, int depth = 0) { if(!node) return; m[order].insert({depth, node->val}); build(node->left, order - 1, depth + 1); build(node->right, order + 1, depth + 1); } public: vector<vector<int>> verticalOrder(TreeNode* root) { build(root); vector<vector<int>> res; transform(m.begin(), m.end(), back_inserter(res), [](auto const& e) { vector<int> _res; transform(e.second.begin(), e.second.end(), back_inserter(_res), [](auto const& _e) {return _e.second;}); return _res; }); return res; } };
|