-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinary_tree.cpp
100 lines (85 loc) · 1.87 KB
/
Binary_tree.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
#include <iostream>
#include <queue>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
int height ;
Node (int val){
data = val;
left = right = nullptr;
height = 1;
}
}
Node* AlmostInsertionBinaryTree(Node *root,int val){
Node *newNode = new Node(val);
if(root==nullptr){
return newNode;
}
queue<Node *>q;
q.push(root);
while(!q.empty()){
Node *temp = q.front();
q.pop();
// left Node inserting
if(temp->left == nullptr){
temp->left=newNode;
return root;
}
else{
q.push(temp->left);
}
// Right Node inserting
if(temp->right == nullptr){
temp->right=newNode;
return root;
}
else{
q.push(temp->right);
}
}
return root;
}
// printing it by'level order traverasal
void printLevelOrder(Node *root){
if(root==nullptr){
return;
}
queue<Node *>q;
q.push(root);
while(!q.empty()){
Node *temp = q.front();
cout<<temp->data<<" ";
q.pop();
if(temp->left!=nullptr){
q.push(temp->left);
}
else if(temp->right!=nullptr){
q.push(temp->right);
}
}
}
int getHeight(Node *root){
if(root==nullptr){
return 0;
}
return root->height;
}
int getbalance(Node *root){
if(root==nullptr){
return 0;
}
return getHeight(root->left) - getHeight(root->right);
}
int main(){
Node* root = nullptr;
AlmostInsertionBinaryTree(root,3);
AlmostInsertionBinaryTree(root,5);
AlmostInsertionBinaryTree(root,4);
AlmostInsertionBinaryTree(root,7);
AlmostInsertionBinaryTree(root,6);
cout<<"Level Order traversal of Binary tree will be"<< endl;
printLevelOrder(root);
}