forked from v100901/hackoctoberfest2020__
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeightOfBinaryTree.cpp
135 lines (119 loc) · 2.81 KB
/
HeightOfBinaryTree.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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class BinaryTreeNode
{
public:
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode(T data)
{
this->data = data;
left = NULL;
right = NULL;
}
~BinaryTreeNode()
{
delete left;
delete right;
}
};
BinaryTreeNode<int> *Take_Input_Level_Wise()
{
int rootData;
cout << "Enter root data: " << endl;
cin >> rootData;
if (rootData == -1)
{
return NULL;
}
BinaryTreeNode<int> *root = new BinaryTreeNode<int>(rootData);
queue<BinaryTreeNode<int> *> pendingNodes;
pendingNodes.push(root);
while (!pendingNodes.empty())
{
BinaryTreeNode<int> *front = pendingNodes.front();
pendingNodes.pop();
int leftChildData;
cout << "Enter left child value of " << front->data << " : " << endl;
cin >> leftChildData;
if (leftChildData != -1)
{
BinaryTreeNode<int> *child = new BinaryTreeNode<int>(leftChildData);
front->left = child;
pendingNodes.push(child);
}
int rightChildData;
cout << "Enter right child value of " << front->data << " : " << endl;
cin >> rightChildData;
if (rightChildData != -1)
{
BinaryTreeNode<int> *child = new BinaryTreeNode<int>(rightChildData);
front->right = child;
pendingNodes.push(child);
}
}
return root;
}
void print_Level_Wise(BinaryTreeNode<int> *root)
{
if (root == NULL)
{
return;
}
queue<BinaryTreeNode<int> *> pendingNodes;
pendingNodes.push(root);
while (!pendingNodes.empty())
{
BinaryTreeNode<int> *front = pendingNodes.front();
pendingNodes.pop();
cout << front->data << " : ";
if (front->left != NULL)
{
cout << "L: " << front->left->data << " , ";
pendingNodes.push(front->left);
}
else
{
cout << "L: " << -1 << " , ";
}
if (front->right != NULL)
{
cout << "R: " << front->right->data;
pendingNodes.push(front->right);
}
else
{
cout << "R: " << -1;
}
cout << endl;
}
}
int Height(BinaryTreeNode<int> *root)
{
if (root == NULL)
{
return 0;
}
int leftHeight = Height(root->left);
int rightHeight = Height(root->right);
if (leftHeight > rightHeight)
{
return 1 + leftHeight;
}
else
{
return 1 + rightHeight;
}
}
int main()
{
BinaryTreeNode<int> *root = Take_Input_Level_Wise();
cout<<endl;
cout<<"Height of Binary tree is : "<<endl;
cout<<Height(root);
cout<<endl;
print_Level_Wise(root);
return 0;
}