Wednesday, March 5, 2014

Root to leaf path with specified sum in a binary tree

The problem here is "To find if there is any root to leaf path with specified sum in a binary tree."

Consider the binary tree shown in the tree below .

We have to find whether there is any path which goes from root to any leaf having sum equal to given sum.
For example if we have given sum as 28 then there can be two paths which has sum 28.
9->8->11 or 9 ->15->4.

Approach 1:
  • Perform the level order traversal. 
  • During  level order traversal find out all the root to leaf paths exists in the tree.
  • Now for each path check if all the nodes sum equals to given sum. 
This approach will require large space to store all the paths formed during level order. Then again we will have to iterate through all the nodes for finding the sum. 

Approach 2:
  • Perform the post order traversal. 
  • During post order traversal maintain stack of the nodes visited and sum so far.
  • If we have reached to leaf then check if sum so far is same as required sum. 
  • If yes.. print the path else pop the current root and continue.
This approach does usages the temporary space but that will always be equal to maximum height of the tree. Also as every node is visited only once the time complexity will be O(n) where n being number of nodes in the tree.
 
Code below shows both ways to check if given sum exists in the any root to leaf path if exists then how to print the path.


struct Node
{
    int data;
    Node * pLeft;
    Node * pRight;
};

//Just check if sum exists

bool CheckIfSumExistInRTLPath(Node * pRoot, int sum, int currentSum)
{
    if (pRoot)
    {
        currentSum += pRoot->data;
        bool left =
CheckIfSumExistInRTLPath((pRoot->pLeft, sum, currentSum);
        bool right =
CheckIfSumExistInRTLPath((pRoot->pRight, sum, currentSum);
        if (!(pRoot->pLeft) && !(pRoot->pRight) && currentSum == sum)
        {
            cout << " Found matching sum at the leaf : " << pRoot->data << endl;
            return true;
        }
        return (left || right);
    }
    return false;
}


//Print the path if provided sum exists

bool GetRTLPathForSum(Node * pRoot, int sum, int currentSum, stack<Node*> & path)
{
    if (pRoot)
    {
        currentSum += pRoot->data;
        path.push(pRoot);
        bool left = GetRTLPathForSum(pRoot->pLeft, sum, currentSum, path);

        bool right = GetRTLPathForSum(pRoot->pRight, sum, currentSum, path);
        if (!(pRoot->pLeft) && !(pRoot->pRight) && currentSum == sum)
        {
            cout  << endl << " Found matching sum at the leaf : " << pRoot->data << "   The PAth : " << endl;
            stack<Node*> temp;
            while (!path.empty())
            {
                Node * node = path.top();
                temp.push(node);
                path.pop();
                cout << node->data << "  ";
            }

            while (!temp.empty())
            {
                path.push(temp.top());
                temp.pop();
            }

            path.pop();
            return true;
        }
        path.pop();
        return (left || right);
    }
    return false;
}

No comments:

Post a Comment