-
Notifications
You must be signed in to change notification settings - Fork 0
/
987. Vertical Order Traversal of a Binary Tree.cpp
52 lines (43 loc) · 1.4 KB
/
987. Vertical Order Traversal of a Binary Tree.cpp
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
41
42
43
44
45
46
47
48
49
50
51
52
// https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/
/**
* 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
{
vector<vector<int>> result;
map<int, vector<pair<int, int>>> nodes;
public:
vector<vector<int>> verticalTraversal(TreeNode *root)
{
dfs(root, 0, 0);
for (auto &pair : nodes)
{
vector<int> current;
sort(pair.second.begin(), pair.second.end(), compare);
for (auto &values : nodes[pair.first])
current.push_back(values.second);
result.push_back(current);
}
return result;
}
void dfs(TreeNode *root, int row, int column)
{
if (root == nullptr)
return;
nodes[column].push_back({row, root->val});
dfs(root->left, row + 1, column - 1);
dfs(root->right, row + 1, column + 1);
}
static bool compare(pair<int, int> &firstPair, pair<int, int> &secondPair)
{
return (firstPair.first < secondPair.first) || (firstPair.first == secondPair.first && firstPair.second < secondPair.second);
}
};