forked from Alialmanea/C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary tree.cpp
95 lines (76 loc) · 1.79 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
//
// main.cpp
// binaty tree
//
// Created by dabbaghıe on 7/29/20.
// Copyright © 2020 dabbaghıe. All rights reserved.
//
#include <iostream>
#include <queue>
using namespace std;
struct Node{
int data;
struct Node *left,*right;
Node (int key){
data = key;
left = right = NULL;
}
};
void inorder(Node *head){
if(head == NULL)
return;
inorder(head ->left);
printf("%d ", head->data);
inorder(head ->right);
}
void preorder(Node *head){
if(head == NULL)
return;
printf("%d ", head->data);
inorder(head ->left);
inorder(head ->right);
}
void postorder(Node *head){
if(head == NULL)
return;
inorder(head ->left);
inorder(head ->right);
printf("%d ", head->data);
}
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);
}
}
int main(int argc, const char * argv[]) {
// insert code here...
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);
insert(root, 12);
printf(" \nInorder traversal : ");
inorder(root);
printf("\npreoredr traversal : ");
preorder(root);
printf("\npostorder traversal : ");
postorder(root);
return 0;
}