-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_Tree.cpp
76 lines (63 loc) · 1.31 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
// C++ program to insert element in binary tree
#include<bits/stdc++.h>
using namespace std;
/* A binary tree node has key, pointer to left child
and a pointer to right child */
struct Node {
int key;
Node *left, *right;
Node (int x)
{
key = x;
left = right = NULL;
}
};
/* Inorder traversal of a binary tree*/
void inorder(Node* temp)
{
if (!temp)
return;
inorder(temp->left);
cout << temp->key << " ";
inorder(temp->right);
}
/*function to insert element in binary tree */
void insert(Node* temp, int key)
{
queue<Node*> q;
q.push(temp);
// Do level order traversal until we find
// an empty place.
while (!q.empty()) {
Node* temp = q.front();
q.pop();
if (!temp->left) {
temp->left = new Node(key);
break;
} else
q.push(temp->left);
if (!temp->right) {
temp->right = new Node(key);
break;
} else
q.push(temp->right);
}
}
// Driver code
int main()
{
Node* root = new Node(10);
root->left = new Node(11);
root->left->left = new Node(7);
root->right = new Node(9);
root->right->left = new Node(15);
root->right->right = new Node(8);
cout << "Inorder traversal before insertion:";
inorder(root);
int key = 12;
insert(root, key);
cout << endl;
cout << "Inorder traversal after insertion:";
inorder(root);
return 0;
}