-
Notifications
You must be signed in to change notification settings - Fork 14
/
tree_vertical_order.cpp
65 lines (55 loc) · 1.36 KB
/
tree_vertical_order.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
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <map>
#include <vector>
#include <iostream>
using namespace std;
struct Node
{
int key;
Node *left, *right;
};
struct Node* newNode(int key)
{
struct Node * node = new Node;
node->key = key;
node->left = node->right = nullptr;
return node;
}
void get_vertical_order(Node * root, int hd, map<int, vector<int>>& m)
{
//pre-order tree traversal
if (root == nullptr)
return;
m[hd].push_back(root->key); //hash table indexed by horizontal distance (hd)
get_vertical_order(root->left, hd-1, m); //decrement hd by 1
get_vertical_order(root->right, hd+1, m); //increment hd by 1
}
void print_vertical_order(Node * root)
{
int hd = 0;
map<int, vector<int>> m;
get_vertical_order(root, hd, m);
for (auto item : m)
{
for (int i=0; i<item.second.size(); ++i)
{
cout << item.second[i] << " ";
}
cout << endl;
}
}
int main()
{
//create a tree
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
root->right->right->right = newNode(9);
cout << "vertical order traversal: " << endl;
print_vertical_order(root);
return 0;
}