-
Notifications
You must be signed in to change notification settings - Fork 1
/
pre_order_iteration.c
110 lines (103 loc) · 1.75 KB
/
pre_order_iteration.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
102
103
104
105
106
107
108
109
110
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
struct node
{
int data;
struct node* right;
struct node* left;
};
struct node* get_newnode(int data){
struct node* newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=data;
newnode->right=newnode->left=NULL;
return newnode;
}
struct node* insert(struct node* root, int data){
if (root==NULL)
{
root=get_newnode(data);
}
else if(root->data>=data){
root->left=insert(root->left,data);
}
else {
root->right = insert(root->right,data);
}
return root;
}
int max(int a,int b){
if (a>b)
{
return a;
}
return b;
}
struct stack{
int top;
struct node* items[101];
};
void push(struct stack* ms, struct node* item){
ms->items[++ms->top]=item;
}
struct node* pop(struct stack* ms){
if (ms->top>-1)
{
return ms->items[(ms->top)--];
}
}
struct node* peek(struct stack ms){
if(ms.top < 0){
//printf("Stack empty\n");
return 0;
}
return ms.items[ms.top];
}
int isempty(struct stack ms){
if (ms.top<0)
{
return 1;
}
return 0;
}
void pre_order(struct node* root){
struct stack ms;
ms.top=-1;
struct node* temp=root;
if (root==NULL)
{
return;
}
push(&ms,root);
//printf("hii\n");
while(!isempty(ms)){
temp=pop(&ms);
//printf("hee\n");
printf("%d ",temp->data );
if (temp->right)
{
push(&ms,temp->right);
}
if (temp->left)
{
push(&ms,temp->left);
}
}
}
int main(int argc, char const *argv[])
{
struct node* root=(struct node*)malloc(sizeof(struct node));
root=NULL;
root=insert(root,50);
root=insert(root,49);
root=insert(root,25);
root=insert(root,20);
root=insert(root,3);
root=insert(root,99);
//int h=find_height(root);
//printf("%d\n",h );
pre_order(root);
//puts("");
return 0;
}