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);
}
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