-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path314.binary-tree-vertical-order.cpp
More file actions
57 lines (53 loc) · 1.43 KB
/
314.binary-tree-vertical-order.cpp
File metadata and controls
57 lines (53 loc) · 1.43 KB
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
53
54
55
56
57
#include <iostream>
#include <vector>
#include <unordered_map>
#include <map>
#include <iterator>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<vector<int>> verticalOrder(TreeNode *root)
{
vector<vector<int>> result;
int position = 0;
map<int, multimap<int, int>> res;
verticalPrint(root, res, position, 0);
for (auto positionIter = res.begin(); positionIter != res.end(); ++positionIter)
{
vector<int> tmp;
for (auto orderIter = positionIter->second.begin(); orderIter != positionIter->second.end(); ++orderIter)
{
tmp.push_back(orderIter->second);
}
result.push_back(tmp);
}
return result;
}
void verticalPrint(TreeNode *root, map<int, multimap<int, int>> &result, int position, int depth)
{
if (root == NULL)
{
return;
}
result[position].insert(make_pair(depth, root->val));
verticalPrint(root->left, result, position - 1, depth + 1);
verticalPrint(root->right, result, position + 1, depth + 1);
}
};