314. Binary Tree Vertical Order Traversal

314. Binary Tree Vertical Order Traversal

Description

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 .

Example 1:

1
2
Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]

Example 2:

1
2
Input: root = [3,9,8,4,0,1,7]
Output: [[4],[9],[3,0,1],[8],[7]]

Example 3:

1
2
Input: root = [1,2,3,4,10,9,11,null,5,null,null,null,null,null,null,null,6]
Output: [[4],[2,5],[1,10,9,6],[3],[11]]

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Hints/Notes

  • 2025/01/14
  • binary tree
  • premium

Solution

Language: C++

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
32
33
34
35
36
37
/**
* 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:
map<int, map<int, vector<int>>> m;

vector<vector<int>> verticalOrder(TreeNode* root) {
dfs(root, 0, 0);
vector<vector<int>> res;
for (auto& [_, mp] : m) {
vector<int> cur;
for (auto& [_, v] : mp) {
cur.insert(cur.end(), v.begin(), v.end());
}
res.push_back(cur);
}
return res;
}

void dfs(TreeNode* root, int level, int order) {
if (!root) {
return;
}
m[order][level].push_back(root->val);
dfs(root->left, level + 1, order - 1);
dfs(root->right, level + 1, order + 1);
}
};