Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Monday, August 14, 2017

Check if sum of child nodes is equal to current


Explanation:

Check for current node fulfilling property

Then create function that add left sum +right sum + value of current node and check this value to main function


Code:

/* A Binary Tree node
class Node
{
    int data;
    Node left, right;
    Node(int item)
    {
        data = item;
        left = right = null;
    }
}
*/
class sumtree
{
    boolean isLeaf(Node x)
    {
        if(x.left==null && x.right==null)
        return true;
        return false;
    }
    int sum(Node x)
    {
        if(x==null)
        return 0;
        return x.data+sum(x.left)+sum(x.right);
    }
boolean isSumTree(Node node)
{
           
        if(node==null || isLeaf(node))
        return true;
        int lsum=sum(node.left);
        int rsum=sum(node.right);
        if((node.data==(lsum+rsum)) && (sum(node.left)!=0) && (sum(node.right)!=0))
        return true;
        return false;
}
}

0 Comments:

Post a Comment

Stats