Wednesday, October 24, 2012

Is there a path from root to leaf that sums up to a value in a binary tree!!

The problem can be solved using two simple recursive calls. As we need to find a path that starts from root and ends at leaf, we can check at every call if we hit a node that is a leaf and if the sum requirement at that point matches the value of that node, then we declare success. And if any such path exists we return true and hence the 'OR' operator in the return statement.
bool sumPath(node* root, int sum)
{
    if(root == NULL)
        return false;
    if(root->lchild == NULL && root->rchild==NULL && root->data == sum)
        return true;
    return (sumPath(root->lchild, sum - root->data) || sumPath(root->rchild, sum - root->data));
}