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

Powered by Blogger.

Tuesday, August 15, 2017

Node val = sum of all children tree


Explanation:
Calling each parent node and then recuing for children node and suming up the values of children then assign this value to parent.

Code:

class hackerranksolutionc{
    int sum=0;
    public boolean isLeaf(Tree x)
    {
        return (x.left==null && x.right==null);
    }
    public void getsum(Tree x)
    {
        if(x==null )
        return ;
        sum+=x.data;
        getsum(x.left);
        getsum(x.right);
     
    }
    public void toSumTree(Tree root){
        if(root==null)
        return;
        sum=0;
        if(isLeaf(root))
        {
            root.data=0;
            return;
        }
        getsum(root);
         root.data=sum-root.data;
         toSumTree(root.left);
         toSumTree(root.right);
    }
}

Method 2:

int toSumTree(Node node)
    {
        if (node == null)
            return 0;

        // Store the old value
        int old_val = node.data;

        node.data = toSumTree(node.left) + toSumTree(node.right);
        return node.data + old_val;
    }

0 Comments:

Post a Comment

Stats