0%

LeetCode 987. Vertical Order Traversal of a Binary Tree

题目

原题在此

Given the root of a binary tree, calculate the vertical order traversal of the binary tree.

For each node at position (x, y), its left and right children will be at positions (x - 1, y - 1) and (x + 1, y - 1) respectively.

The vertical order traversal of a binary tree is a list of non-empty reports for each unique x-coordinate from left to right. Each report is a list of all nodes at a given x-coordinate. The report should be primarily sorted by y-coordinate from highest y-coordinate to lowest. If any two nodes have the same y-coordinate in the report, the node with the smaller value should appear earlier.

Return the vertical order traversal of the binary tree.

Example 1:

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

Explanation: Without loss of generality, we can assume the root node is at position (0, 0):
The node with value 9 occurs at position (-1, -1).
The nodes with values 3 and 15 occur at positions (0, 0) and (0, -2).
The node with value 20 occurs at position (1, -1).
The node with value 7 occurs at position (2, -2).

Example 2:

Input: root = [1,2,3,4,5,6,7]
Output: [[4],[2],[1,5,6],[3],[7]]

Explanation: The node with value 5 and the node with value 6 have the same position according to the given scheme.
However, in the report [1,5,6], the node with value 5 comes first since 5 is smaller than 6.

Constraints:

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

解析

代码

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
38
39
40
/**
* 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:
struct Foo {
TreeNode* node;
int x;
int y;
};
vector<vector<int>> verticalTraversal(TreeNode* root) {
map<int, map<int, multiset<int>>> mp;
queue<Foo> q;
q.push({root, 0, 0});
while (!q.empty()) {
Foo tmp = q.front();
q.pop();
if(tmp.node -> left ) {q.push({tmp.node -> left , tmp.x - 1, tmp.y - 1});}
if(tmp.node -> right) {q.push({tmp.node -> right, tmp.x + 1, tmp.y - 1});}
mp[tmp.x][tmp.y].insert(tmp.node -> val);
}
vector<vector<int>> res;
for (auto & [key, val] : mp) {
vector<int> tmp;
for (auto & [nonUsed, set] : val) {
tmp.insert(tmp.begin(), set.begin(), set.end());
}
res.push_back(tmp);
}
return res;
}
};