-
Notifications
You must be signed in to change notification settings - Fork 0
/
sunTree.cpp
45 lines (36 loc) · 1.12 KB
/
sunTree.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
class Solution
{
public:
pair<bool,int> isSumTreeFast(Node* root) {
//base case
if(root == NULL) {
pair<bool,int> p = make_pair(true, 0);
return p;
}
if(root->left == NULL && root->right == NULL ) {
pair<bool,int> p = make_pair(true, root->data);
return p;
}
pair<bool,int> leftAns = isSumTreeFast(root->left);
pair<bool,int> rightAns = isSumTreeFast(root->right);
bool isLeftSumTree = leftAns.first;
bool isRightSumTree = rightAns.first;
int leftSum = leftAns.second;
int rightSum = rightAns.second;
bool condn = root->data == leftSum + rightSum;
pair<bool, int> ans;
if(isLeftSumTree && isRightSumTree && condn) {
ans.first = true;
ans.second = root->data + leftSum + rightSum ;
}
else
{
ans.first = false;
}
return ans;
}
bool isSumTree(Node* root)
{
return isSumTreeFast(root).first;
}
};