-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChildrenSum.java
More file actions
62 lines (50 loc) · 1.76 KB
/
Copy pathChildrenSum.java
File metadata and controls
62 lines (50 loc) · 1.76 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
package day31;
public class ChildrenSum {
static class CNode {
int data;
CNode left, right;
CNode(int x) {
data = x;
left = right = null;
}
}
static class Sum {
static int isSumProperty(CNode root) {
// If root is NULL or it's a leaf node
// then return true
if (root == null || (root.left == null && root.right == null))
return 1;
int sum = 0;
// If left child is not present then 0
// is used as data of left child
if (root.left != null)
sum += root.left.data;
// If right child is not present then 0
// is used as data of right child
if (root.right != null)
sum += root.right.data;
// if the node and both of its children
// satisfy the property return 1 else 0
return ((root.data == sum)
&& (isSumProperty(root.left) == 1)
&& (isSumProperty(root.right) == 1)) ?
1 : 0;
}
public static void main(String[] args) {
// Create a hard-coded tree.
// 35
// / \
// 20 15
// / \ / \
// 15 5 10 5
CNode root = new CNode(35);
root.left = new CNode(20);
root.right = new CNode(15);
root.left.left = new CNode(15);
root.left.right = new CNode(5);
root.right.left = new CNode(10);
root.right.right = new CNode(5);
System.out.println(isSumProperty(root));
}
}
}