Thursday 9 May 2013

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

/*
    1.    Idea is to use inorder traversal algorithm.
    2.    Set variable present = false it is set to true as soon as we find the leaf element at which sum from root to this element is equal to val.
    3.    After present =true no more recursive calls are made it is ensure by
    if present then return.
    4.    After leaf element with sum from root to it equal to val is found no more recursive calls will be made. print these previously made calls as they will trace back to root node from search element.
    5.    If present == true then print node->data.
*/   
   
    bool present;
    void leafSum(node *ptr, int val)
    {
        if(present)
            return;
        if(ptr)
        {
            // LEAF NODE
              if(ptr->getLeftChild() == NULL && ptr->getRightChild() == NULL)
              {
                  if(val - ptr->getData() == 0)
                  {
                      cout<<"PRESENT";
                      present = true;
                  }
              }
              leafSum(ptr->getLeftChild(), val - ptr->getData());
              leafSum(ptr->getRightChild(), val - ptr->getData());
              if(present)
                  cout<<"  "<<ptr->getData();
        }
        
    }

No comments:

Post a Comment