-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumTree.java
More file actions
39 lines (29 loc) · 822 Bytes
/
SumTree.java
File metadata and controls
39 lines (29 loc) · 822 Bytes
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
package Trees;
public class SumTree {
static boolean f = true;
public static int check(Node root) {
int s = 0;
if (root == null) return 0;
if (root.left == null && root.right == null) return root.val;
int l = check(root.left);
int r = check(root.right);
if (l + r != root.val) f = false;
return l + r + root.val;
}
static boolean isSumTree(Node root) {
check(root);
return f;
}
int sumTree(Node root) {
if (root == null) return 0;
int leftSum = sumTree(root.left);
int rightSum = sumTree(root.right);
int x = root.val;
int tSum = leftSum + rightSum;
root.val = tSum;
return tSum + x;
}
public void toSumTree(Node root) {
sumTree(root);
}
}