File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n)
2
+ // Space: O(n)
3
+
4
+ /* *
5
+ * Definition for a binary tree node.
6
+ * struct TreeNode {
7
+ * int val;
8
+ * TreeNode *left;
9
+ * TreeNode *right;
10
+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11
+ * };
12
+ */
13
+ class Solution {
14
+ public:
15
+ vector<vector<int >> verticalOrder (TreeNode* root) {
16
+ unordered_map<int , vector<int >> cols;
17
+ vector<pair<TreeNode *, int >> queue{{root, 0 }};
18
+ for (int i = 0 ; i < queue.size (); ++i) {
19
+ TreeNode *node;
20
+ int j;
21
+ tie (node, j) = queue[i];
22
+ if (node) {
23
+ cols[j].emplace_back (node->val );
24
+ queue.push_back ({node->left , j - 1 });
25
+ queue.push_back ({node->right , j + 1 });
26
+ }
27
+ }
28
+ int min_idx = numeric_limits<int >::max (),
29
+ max_idx = numeric_limits<int >::min ();
30
+ for (const auto & kvp : cols) {
31
+ min_idx = min (min_idx, kvp.first );
32
+ max_idx = max (max_idx, kvp.first );
33
+ }
34
+ vector<vector<int >> res;
35
+ for (int i = min_idx; !cols.empty () && i <= max_idx; ++i) {
36
+ res.emplace_back (cols[i]);
37
+ }
38
+ return res;
39
+ }
40
+ };
You can’t perform that action at this time.
0 commit comments