-
Notifications
You must be signed in to change notification settings - Fork 1
/
treetraversal.cpp
99 lines (81 loc) · 2.11 KB
/
treetraversal.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
// C++ program to insert element in Binary Tree
#include <iostream>
#include <queue>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
int data;
Node* left;
Node* right;
};
/* Function to create a new node */
Node* CreateNode(int data)
{
Node* newNode = new Node();
if (!newNode) {
cout << "Memory error\n";
return NULL;
}
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
/* Function to insert element in binary tree */
Node* InsertNode(Node* root, int data)
{
// If the tree is empty, assign new node address to root
if (root == NULL) {
root = CreateNode(data);
return root;
}
// Else, do level order traversal until we find an empty
// place, i.e. either left child or right child of some
// node is pointing to NULL.
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* temp = q.front();
q.pop();
if (temp->left != NULL)
q.push(temp->left);
else {
temp->left = CreateNode(data);
return root;
}
if (temp->right != NULL)
q.push(temp->right);
else {
temp->right = CreateNode(data);
return root;
}
}
}
/* Inorder traversal of a binary tree */
void inorder(Node* temp)
{
if (temp == NULL)
return;
inorder(temp->left);
cout << temp->data << ' ';
inorder(temp->right);
}
// Driver code
int main()
{
Node* root = CreateNode(10);
root->left = CreateNode(11);
root->left->left = CreateNode(7);
root->right = CreateNode(9);
root->right->left = CreateNode(15);
root->right->right = CreateNode(8);
cout << "Inorder traversal before insertion: ";
inorder(root);
cout << endl;
int key = 12;
root = InsertNode(root, key);
cout << "Inorder traversal after insertion: ";
inorder(root);
cout << endl;
return 0;
}