-
Notifications
You must be signed in to change notification settings - Fork 0
/
TreeAllOperations.cpp
146 lines (103 loc) · 2.84 KB
/
TreeAllOperations.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
136
137
138
139
140
141
142
143
144
145
146
#include<iostream>
#include<queue>
using namespace std;
class Node{
public:
int val;
Node* left;
Node* right;
Node(int val){
this->val = val;
left = right = nullptr;
}
};
class BinaryTree{
int numberOfNodes;
public:
BinaryTree(){
numberOfNodes = 0;
}
Node* buildTree(Node*&);
void preOrder(Node*);
void inOrder(Node*);
void postOrder(Node*);
void levelOrder(Node*);
int getNoOfNodes(Node*);
int maxHeight(Node*);
};
int BinaryTree :: getNoOfNodes(Node*root){
return numberOfNodes;
}
Node* BinaryTree :: buildTree(Node* &root){
cout << "\nEnter the data : ";
int data;
cin >> data;
// Create a root node or initalise it
root = new Node(data);
if(data==-1) return NULL;
cout << "Enter data to be inserted to the left of " << data << " " ;
root->left = buildTree(root->left);
cout << "Enter data to be inserted to the right of " << data << " " ;
root->right = buildTree(root->right);
return root;
}
void BinaryTree :: preOrder(Node* root){
if(!root) return;
// Preorder=> (Root , Left , Right)
cout << root->val << " " ;
preOrder(root->left);
preOrder(root->right);
}
void BinaryTree :: inOrder(Node* root){
if(!root) return ;
// Inorder => (Left Root Right)
inOrder(root->left);
cout << root->val << " " ;
inOrder(root->right);
}
void BinaryTree :: postOrder(Node* root){
if(!root) return;
// PostOrderr => (Left , Right , Root)
postOrder(root->left);
postOrder(root->right);
cout << root->val << " " ;
numberOfNodes++;
}
void BinaryTree :: levelOrder(Node* root){
if(!root) return;
queue<Node*>qu;
qu.push(root);
while(!qu.empty()){
int queueSize = qu.size();
for(int i=0;i<queueSize;i++){
Node* Front = qu.front();
qu.pop();
if(Front->left) qu.push(Front->left);
if(Front->right) qu.push(Front->right);
cout << Front->val << " " ;
}
cout << endl;
}
}
int BinaryTree :: maxHeight(Node* root){
if(!root) return 0;
int lh = maxHeight(root->left);
int rh = maxHeight(root->right);
return 1+max(lh,rh) ;
}
int main(){
BinaryTree bt;
Node* root = NULL;
bt.buildTree(root);
cout << "\nPre-order traversal : " ;
bt.preOrder(root);
cout << "\nIn-order traversal : " ;
bt.inOrder(root);
cout << "\nPost-order traversal : " ;
bt.postOrder(root);
cout << "\n\nLevel order traversal : \n";
bt.levelOrder(root);
cout << "\nNumber of nodes in tree : " << bt.getNoOfNodes(root) << endl;
cout << "height of binary tree is " << bt.maxHeight(root) << endl;
return 0;
}