-
Notifications
You must be signed in to change notification settings - Fork 0
/
bottom_view_of_a_binary_tree.java
100 lines (86 loc) · 2.46 KB
/
bottom_view_of_a_binary_tree.java
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// C++ Program to print Bottom View of Binary Tree
#include<bits/stdc++.h>
using namespace std;
// Tree node class
struct Node
{
int data; //data of the node
int hd; //horizontal distance of the node
Node *left, *right; //left and right references
// Constructor of tree node
Node(int key)
{
data = key;
hd = INT_MAX;
left = right = NULL;
}
};
// Method that prints the bottom view.
void bottomView(Node *root)
{
if (root == NULL)
return;
// Initialize a variable 'hd' with 0
// for the root element.
int hd = 0;
// TreeMap which stores key value pair
// sorted on key value
map<int, int> m;
// Queue to store tree nodes in level
// order traversal
queue<Node *> q;
// Assign initialized horizontal distance
// value to root node and add it to the queue.
root->hd = hd;
q.push(root);
// Loop until the queue is empty (standard
// level order loop)
while (!q.empty())
{
Node *temp = q.front();
q.pop();
// Extract the horizontal distance value
// from the dequeued tree node.
hd = temp->hd;
// Put the dequeued tree node to TreeMap
// having key as horizontal distance. Every
// time we find a node having same horizontal
// distance we need to replace the data in
// the map.
m[hd] = temp->data;
// If the dequeued node has a left child, add
// it to the queue with a horizontal distance hd-1.
if (temp->left != NULL)
{
temp->left->hd = hd-1;
q.push(temp->left);
}
// If the dequeued node has a right child, add
// it to the queue with a horizontal distance
// hd+1.
if (temp->right != NULL)
{
temp->right->hd = hd+1;
q.push(temp->right);
}
}
// Traverse the map elements using the iterator.
for (auto i = m.begin(); i != m.end(); ++i)
cout << i->second << " ";
}
// Driver Code
int main()
{
Node *root = new Node(20);
root->left = new Node(8);
root->right = new Node(22);
root->left->left = new Node(5);
root->left->right = new Node(3);
root->right->left = new Node(4);
root->right->right = new Node(25);
root->left->right->left = new Node(10);
root->left->right->right = new Node(14);
cout << "Bottom view of the given binary tree :\n"
bottomView(root);
return 0;
}