Print all the paths from root, with a specified sum in Binary tree

2.9

Given a Binary tree and a sum S, print all the paths, starting from root, that sums upto the given sum.

Note that this problem is different from root to leaf paths. Here path doesn’t need to end on a leaf node.

Examples:

Input : 
Input : sum = 8, 
        Root of tree
         1
       /   \
     20      3
           /    \
         4       15    
        /  \     /  \
       6    7   8    9           
Output :
Path: 1 3 4

Input : sum = 38,
        Root of tree
          10
       /     \
     28       13
           /     \
         14       15
        /   \     /  \
       21   22   23   24
Output : Path found: 10 28 
        Path found: 10 13 15  

For this problem, preorder traversal is best suited as we have to add up a key value as we land on that node.

We start from the root and start traversing by preorder traversal, adding key value to the sum_so_far and checking whether it is equal to the required sum.
Also, as tree node doesn’t have a pointer pointing to its parent, we have to explicitly save from where we have moved. We use a vector path to store the path for this.

Every node in this path contributes to the sum_so_far.

// C++ program to print all paths begiinning with
// root and sum as given sum
#include<bits/stdc++.h>
using namespace std;

// A Tree node
struct Node
{
    int key;
    struct Node *left, *right;
};

// Utility function to create a new node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}


void printPathsUtil(Node* curr_node, int sum,
             int sum_so_far, vector<int> &path)
{
    if (curr_node == NULL)
        return;

    // add the current node's value
    sum_so_far += curr_node->key;

    // add the value to path
    path.push_back(curr_node->key);

    // print the required path
    if (sum_so_far == sum )
    {
        cout << "Path found: ";
        for (int i=0; i<path.size(); i++)
            cout << path[i] << " ";

        cout << endl;
    }

    // if left child exists
    if (curr_node->left != NULL)
        printPathsUtil(curr_node->left, sum, sum_so_far, path);

    // if right child exists
    if (curr_node->right != NULL)
        printPathsUtil(curr_node->right, sum, sum_so_far, path);


    // Remove last element from path
    // and move back to parent
    path.pop_back();
}

// Wrapper over printPathsUtil
void printPaths(Node *root, int sum)
{
    vector<int> path;
    printPathsUtil(root, sum, 0, path);
}

// Driver program
int main ()
{
    /*   10
       /     \
     28       13
           /     \
         14       15
        /   \     /  \
       21   22   23   24*/
    Node *root  = newNode(10);
    root->left  = newNode(28);
    root->right = newNode(13);

    root->right->left   = newNode(14);
    root->right->right  = newNode(15);

    root->right->left->left   = newNode(21);
    root->right->left->right  = newNode(22);
    root->right->right->left  = newNode(23);
    root->right->right->right = newNode(24);

    int sum = 38;

    printPaths(root, sum);

    return 0;
}

Output:

Path found: 10 28 
Path found: 10 13 15 

This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2.9 Average Difficulty : 2.9/5.0
Based on 11 vote(s)