Skip to content

Instantly share code, notes, and snippets.

@anil477
Created June 30, 2017 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/89f3d3a0f9a71fdd5fe5b8b6b2a8f0f9 to your computer and use it in GitHub Desktop.
Save anil477/89f3d3a0f9a71fdd5fe5b8b6b2a8f0f9 to your computer and use it in GitHub Desktop.
Check for Children Sum Property in a Binary Tree
// Given a binary tree, write a function that returns true if the tree satisfies below property.
// For every node, data value must be equal to sum of data values in left and right children. Consider data value as 0 for NULL children.
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
class BinaryTree {
Node root;
public void checkSum() {
System.out.println(" Result " + sum(root));
}
public int sum(Node root){
if(root==null || (root.left == null && root.right == null)) {
return 1;
}
int left = 0;
int right = 0;
if(root.left !=null) {
left = root.left.data;
}
if(root.right !=null) {
right = root.right.data;
}
if( (left + right) == root.data && sum(root.left)!=0 && sum(root.right)!=0 ){
return 1;
} else{
return 0;
}
}
public static void main(String args[]) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(8);
tree.root.right = new Node(2);
tree.root.left.left = new Node(3);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(2);
tree.checkSum();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment