-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary tree.c
101 lines (98 loc) · 2.26 KB
/
binary tree.c
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
#include<stdio.h>
#include<stdlib.h>
struct t_node{
int data;
struct t_node *left;
struct t_node *right;
};
typedef struct t_node TreeNode;
//creating a function that creates a trees and puts value in it
TreeNode *create_tree_node(int val){
TreeNode *nn=(TreeNode *)malloc(sizeof(TreeNode));
nn->data=val;
nn->left=NULL;
nn->right=NULL;
return nn;
}
//void pre_order(TreeNode *root){
// if(root!=NULL){
// printf("%d ",root->data);
// pre_order(root->left);
// pre_order(root->right);
// }
//}
//void in_order(TreeNode *root){
// if(root!=NULL){
// in_order(root->left);
// printf("%d ",root->data);
// in_order(root->right);
// }
//}
//void post_order(TreeNode *root){
// if(root!=NULL){
// post_order(root->left);
// post_order(root->right);
// printf("%d ",root->data);
// }
//}
void level_order(TreeNode *root){
TreeNode *q[100];///queue of trees nodes
int front,rear;
front=0;
rear=1;
q[0]=root;//inserting root intoqueue
while(front!=rear){
TreeNode *dn=q[front++];//deque
printf("%d ",dn->data);
//checkif deleted node is having left child
if(dn->left!=NULL){
q[rear++]=dn->left;
}
//checkif deleted node is having rigth child
if(dn->right!=NULL){
q[rear++]=dn->right;
}
///optional
dn=NULL;
free(dn);
}
}
int main(){
//creating tree node
TreeNode *n1,*n2,*n3,*n4,*n5,*n6,*n7,*n8,*n9;
n1=create_tree_node(10);
n2=create_tree_node(20);
n3=create_tree_node(30);
n4=create_tree_node(40);
n5=create_tree_node(50);
n6=create_tree_node(60);
n7=create_tree_node(70);
n8=create_tree_node(80);
n9=create_tree_node(90);
//making connnection
n1->left=n2;
n1->right=n3;
n2->left=n4;
n2->right=n5;
n3->left=n6;
n3->right=n7;
n4->right=n8;
n7->left=n9;
// pre_order(n1);
printf("\n");
level_order(n1);
printf("\n");
// in_order(n1);
printf("\n");
// post_order(n1);
printf("\n");
// printf("%d\n",n1->data);
// printf("%d\n",n1->left->data);
// printf("%d\n",n1->right->data);
// printf("%d\n",n1->left->left->data);
// printf("%d\n",n1->left->right->data);
// printf("%d\n",n1->right->left->data);
// printf("%d\n",n1->right->right->data);
// printf("%d\n",n1->left->left->right->data);
// printf("%d\n",n1->right->right->left->data);
}