-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumTree.java
More file actions
44 lines (38 loc) · 1.36 KB
/
SumTree.java
File metadata and controls
44 lines (38 loc) · 1.36 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
package com.interview.tree;
class Count{
int size;
}
/**
* http://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree/
* A SumTree is a Binary Tree where the value of a node is equal to sum of the nodes present
* in its left subtree and right subtree
*/
public class SumTree {
public boolean isSumTree(Node root){
Count count = new Count();
return isSumTree(root,count);
}
private boolean isSumTree(Node root,Count count){
if(root == null){
return true;
}
if(root.left == null && root.right == null){
count.size = root.data;
return true;
}
Count leftCount = new Count();
Count rightCount = new Count();
boolean isLeft = isSumTree(root.left,leftCount);
boolean isRight = isSumTree(root.right,rightCount);
count.size = root.data + leftCount.size + rightCount.size;
return isLeft && isRight && root.data == (leftCount.size + rightCount.size);
}
public static void main(String args[]){
ConstructTreeFromInOrderPreOrder ctf = new ConstructTreeFromInOrderPreOrder();
int inorder[] = {4,10,6,46,11,13,2};
int preorder[] = {46,10,4,6,13,11,2};
Node root = ctf.createTree(inorder, preorder);
SumTree st = new SumTree();
System.out.println(st.isSumTree(root));
}
}