Topic: Tree
1) Children Sum Parent | Easy |
RECURSIVE SOLUTION
Input:
1
/ \
4 3
/ \
5 N
Output: 0
Explanation: Here, 1 is the root node
and 4, 3 are its child nodes. 4 + 3 =
7 which is not equal to the value of
root node. Hence, this tree does not
satisfy the given conditions.
public static int isSumProperty(Node root)
{
int x,y,sum=0;
if(root==null){return 1;}
if(root.left==null && root.right==null){return 1;}
if(root.left!=null){sum = sum + root.left.data;}
if(root.right!=null){sum = sum + root.right.data;}
if(root.data==sum){
return (isSumProperty(root.left) & isSumProperty(root.right)); // bitwise
}
return 0;
}
}
Thank you for reading :)