-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLevelsOfNode.cpp
168 lines (124 loc) · 2.72 KB
/
LevelsOfNode.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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// binary search tree
#include<bits/stdc++.h>
using namespace std;
// in structure all the public access is by default
class Node
{
public:
int data;
Node* left;
Node* right;
Node(){
left=NULL;
right=NULL;
}
Node(int val){
data=val;
left=NULL;
right=NULL;
}
};
Node* newNode(int val){
Node* n; // pointer to the class
n=new Node(val); // memory block of the class
return n;
}
Node* insert(Node* root,int val){
if(root==NULL){
root=newNode(val);
}
else if( val > root->data){
root->right = insert(root->right,val);
}
else if(val < root->data){
root->left = insert(root->left,val);
}
//return root;
}
// preorder DLR
void preorder(Node* root){
if(root){
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
}
// height of the tree
int height(Node* root ){
if(root==NULL){
return -1;
}
else{
int lheight = height(root->left);
int rheight = height(root->right);
if(lheight > rheight)
return(lheight+1);
else
return(rheight+1);
}
}
void preorderS(Node* root){ // DLR using Stack
stack<Node*>s;
if(!root)
return;
s.push(root);
while(!s.empty()){
Node* temp = s.top();s.pop();
cout<<temp->data<<" ";
if(temp->right)
s.push(temp->right);
if(temp->left)
s.push(temp->left);
}
}
// Levelling each node in the tree
void levelNodes(Node* root){
int level[10];
queue<Node*>q;
q.push(root);
for(int i=0;i<10;i++){
level[i]=-1;
}
level[root->data]=0;
while(!q.empty()){
Node* temp = q.front(); q.pop();
if(temp->left){
q.push(temp->left);
level[temp->left->data] = level[temp->data]+1;
}
if(temp->right){
q.push(temp->right);
level[temp->right->data] = level[temp->data]+1;
}
}
for(int i=0;i<10;i++){
if(level[i]!=-1)
cout<<level[i]<<" ";
}
cout<<endl;
}
Node* find(Node* root,int data){
if(!root)
return NULL;
if(root->data > data)
return find(root->left,data);
else if(root->data < data)
return find(root->right,data);
return root;
}
int main(){
Node* root = NULL;
root=insert(root,6);
root=insert(root,4);
root=insert(root,5);
root=insert(root,3);
root=insert(root,8);
root=insert(root,9);
root=insert(root,7);
cout<<"Preorder"<<endl;
preorderS(root);
cout<<endl;
cout<<height(root)<<endl;
cout<<"Levels of each Node"<<endl;
levelNodes(root);
}