-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrint all root to leaf paths in the binary search tree
114 lines (107 loc) · 1.76 KB
/
Print all root to leaf paths in the binary search tree
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
Implement a C program to print all the root to leaf paths in the binary search tree
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
void printPaths(struct node* );
void printArray(int[],int);
void printPathsRecur(struct node*,int[],int);
void insert(struct node **,int);
void display(struct node *);
int main()
{
int d;
char ch[10];
struct node *root=NULL;
do
{
printf("Enter the element to be inserted\n");
scanf("%d",&d);
insert(&root,d);
printf("Do you want to insert another element\n");
scanf("%s",ch);
}while(!strcmp(ch,"Yes"));
printf("The elements are");
display(root);
printf("\nPaths from root to leaf node:\n");
printPaths(root);
return 0;
}
void insert(struct node **root,int data)
{
struct node * n= (struct node*)malloc(sizeof(struct node));
n->data=data;
n->left=NULL;
n->right=NULL;
if(*root==NULL)
{
*root=n;
}
else
{
struct node *temp,*prev;
temp=*root;
while(temp!=NULL)
{
prev=temp;
if(temp->data>data)
{
temp=temp->left;
}
else
{
temp=temp->right;
}
}
if((prev->data)>data)
{
prev->left=n;
}
else
{
prev->right=n;
}
}
}
void display(struct node *s)
{
if(s!=NULL)
{
display(s->left);
printf(" %d",s->data);
display(s->right);
}
}
void printPaths(struct node* node)
{
int path[1000];
printPathsRecur(node, path, 0);
}
void printPathsRecur(struct node* node, int path[], int pathLen)
{
if(node==NULL){
return;
}
path[pathLen] = node->data;
pathLen++;
if(node->left==NULL && node->right==NULL){
printArray(path,pathLen);
}
else{
printPathsRecur(node->left,path,pathLen);
printPathsRecur(node->right,path,pathLen);
}
}
void printArray(int ints[], int len)
{
int i;
for (i=0; i<len; i++) {
printf("%d ", ints[i]);
}
printf("\n");
}