forked from vivekanand44/codes-Youtube-videos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
root to leaf paths.cpp
120 lines (99 loc) · 1.51 KB
/
root to leaf paths.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *left;
struct node *right;
}node;
int path[20];
int top = -1;
void print_stack()
{
int i;
printf("\n");
printf("Path ==> ");
for(i=0;i<=top;i++)
{
printf(" %d",path[i]);
}
}
void push(int a)
{
top++;
path[top] = a;
}
void pop()
{
printf("\n %d is popped",path[top]);
top--;
}
void find_root_to_leaf_paths(node *root)
{
if(root == NULL)
return;
push(root->data);
find_root_to_leaf_paths(root->left);
if(root->left == NULL && root->right == NULL)
print_stack();
find_root_to_leaf_paths(root->right);
pop();
}
void inorder(node *root)
{
if(root)
{
inorder(root->left);
printf(" %d" , root->data );
inorder(root->right);
}
}
int main()
{
node *p,*q , *root;
int i, n , k , path[20],flag=0;
printf("Enter the number of elements");
scanf("%d",&n);
p = (node*)malloc(sizeof(node));
p->left = NULL;
p->right = NULL;
printf("Enter the number");
scanf("%d",&p->data);
root = p;
for(i = 1 ;i<n;i++)
{
q = (node*)malloc(sizeof(node));
q->left = NULL;
q->right = NULL;
printf("Enter the number");
scanf("%d",&q->data);
p = root;
while(true)
{
if (q->data > p->data)
{
if(p->right == NULL)
{
p->right = q;
break;
}
p = p->right;
}
else
{
if(p->left == NULL)
{
p->left = q;
break;
}
p = p->left;
}
}
}
inorder(root);
find_root_to_leaf_paths(root);
// printf("\n Tha maximum is %d",getmax(root));
getch();
return 0;
}