-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4-8TreeSum.cpp
More file actions
132 lines (122 loc) · 1.91 KB
/
4-8TreeSum.cpp
File metadata and controls
132 lines (122 loc) · 1.91 KB
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
121
122
123
124
125
126
127
128
129
130
//Write a function to find out whether there is a path from root to leaf with sum equal to given Number
//mirror the tree
//print tree levelwise
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<process.h>
typedef struct node
{
node *LC;
int data;
node *RC;
node()
{
LC=NULL;
data=0;
RC=NULL;
}
}BST;
class tree
{
private:
BST *root;
public:
tree()
{
root=NULL;
}
BST* getroot()
{
return root;
}
void addnode(int val)
{
BST *cur,*p,*q;
p=new node;
p->data=val;
p->LC=p->RC=NULL;
if(root==NULL)
{
root=p;
printf("\nValue added in tree!!");
getch();
}
else
{
cur=root;
while(cur!=NULL)
{
if(val==cur->data)
{
printf("element aleady exists");
return;
}
else if(val>cur->data)
{
q=cur;
cur=cur->RC;
}
else
{
q=cur;
cur=cur->LC;
}
}
if(val>q->data)
q->RC=p;
else
q->LC=p;
}
}
bool pathWithGivenSum(BST *root,int sum)
{
// return true if we run out of tree and sum==0
if(root==NULL)
return (sum==0);
if(root->LC==NULL && root->RC==NULL)
return (sum==root->data);
int currentSum = sum - root->data;
if(root->LC && pathWithGivenSum(root->LC,currentSum))
return true;
if(root->RC && pathWithGivenSum(root->RC,currentSum))
return true;
return false;
}
void mirror(BST *t)
{
BST *q;
if(t)
{
q=t->LC;
t->LC=t->RC;
t->RC=q;
mirror(t->LC);
mirror(t->RC);
}
}
};
void main()
{
tree R,root;
bool result;
int i,data,n,sum;
clrscr();
printf("\nEnter the number of nodes to be Added to the tree \n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter data : ");
scanf("%d",&data);
addnode(data);
}
printf("\n Enter the sum : ");
scanf("%d",&sum);
root=R.getroot();
result=pathWithGivenSum(root,sum);
if(result==TRUE)
printf("\n There Exists a path");
else
printf("\n There dosrn't exist path for the given sum");
getch();
}