-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbt_checksum.cpp
139 lines (106 loc) · 1.88 KB
/
bt_checksum.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef struct node st;
struct node
{
ll data;
st *left,*right;
};
st* newnode(ll data)
{
st* temp=(st*)malloc(sizeof(st));
temp->data=data;
temp->left=temp->right=NULL;
return temp;
}
ll height(st* root)
{
ll lheight,rheight;
if(root==NULL)
{
return 0;
}
else
{
lheight=height(root->left);
rheight=height(root->right);
if(lheight>rheight)
return lheight+1;
else
rheight+1;
}
}
ll diameter(st *root)
{
ll ans;
if(root==NULL)
{
return 0;
}
ll lheight,rheight;
lheight=height(root->left);
rheight=height(root->right);
ll ldiam=diameter(root->left);
ll rdiam=diameter(root->right);
return max(lheight+rheight+1,max(ldiam,rdiam));
}
int check(st* node,int subsum)
{
if(node==NULL)
{
return (subsum==0);
}
else
{
bool ans=0;
int sum=subsum - node->data;
if(sum==0 && node->left==NULL && node->right==NULL)
{
return 1;
}
if(node->left)
{
ans=ans || check(node->left,sum);
}
if(node->right)
{
ans=ans || check(node->right,sum);
}
return ans;
}
}
bool hasPathSum(struct node* node, int sum)
{
/* return true if we run out of tree and sum==0 */
if (node == NULL)
{
return (sum == 0);
}
else
{
bool ans = 0;
/* otherwise check both subtrees */
int subSum = sum - node->data;
/* If we reach a leaf node and sum becomes 0 then return true*/
if ( subSum == 0 && node->left == NULL && node->right == NULL )
return 1;
if(node->left)
ans = ans || hasPathSum(node->left, subSum);
if(node->right)
ans = ans || hasPathSum(node->right, subSum);
return ans;
}
}
int main()
{
st *root=NULL;
root=newnode(10);
root->left=newnode(8);
root->right=newnode(2);
root->left->left=newnode(3);
root->left->right=newnode(5);
cout<<check(root,21);
cout<<hasPathSum(root,21);
return 0;
}