-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCheck for Children Sum Property in a Binary Tree.cpp
82 lines (68 loc) · 1.54 KB
/
Check for Children Sum Property in a Binary Tree.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
/* Method - 1
DFS - recursion
Time complexity - O(N)
Space complexity- O(height of tree)
*/
class Solution{
public:
bool help(Node* root)
{
//base case
if(!root)
return 1;
if(root->left==NULL and root->right==NULL)
return 1;
//recursive calls
//and small calculation
int sum=0;
if(root->left)
sum+=root->left->data;
if(root->right)
sum+=root->right->data;
if(sum!=root->data)
return 0;
bool a=help(root->left);
if(!a)
return 0;
bool b=help(root->right);
return b;
}
int isSumProperty(Node *root)
{
return int(help(root));
}
};
/* Method - 2
BFS - queue
Time complexity - O(N)
Space complexity- O(N)
*/
class Solution{
public:
int isSumProperty(Node *root)
{
queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node* node=q.front();
q.pop();
if(node->left==NULL and node->right==NULL)
continue;
int sum=0;
if(node->left)
{
sum+=node->left->data;
q.push(node->left);
}
if(node->right)
{
sum+=node->right->data;
q.push(node->right);
}
if(sum!=(node->data))
return 0;
}
return 1;
}
};