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

Powered by Blogger.

Friday, September 8, 2017

Root to leaf path sum


Problem:

You are given root of tree and sum k,
Find if k==sum of path from root to leaf

Code:

 boolean isLeaf(Node node)
    {
        if(node.left==null && node.right==null)
        return true;
        return false;
    }
    boolean hasPathSum(Node node, int sum)
    {
        if(node==null || sum<0)
        return false;
        if(sum==node.data && isLeaf(node))
        return true;
       return  hasPathSum(node.left,sum-node.data) || hasPathSum(node.right,sum-node.data);
    }

0 Comments:

Post a Comment

Stats