Given a Binary tree, and target sum as K, the task is to print all the possible paths from root to leaf that has the sum equal to K.
Examples:
Input: K = 22
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Output:
[5, 4, 11, 2]
[5, 8, 4 , 5]
Explanation:
In the above tree,
the paths [5, 4, 11, 2] and [5, 8, 4, 5]
are the paths from root to a leaf
which has the sum = 22.
Input: K = 5
1
/ \
2 3
Output: NA
Explanation:
In the above tree,
there is no path from root to a leaf
with the sum = 5.
Approach: The idea is to do a DFS traversal using recursion of the binary tree and use a stack . Follow the steps below to implement the approach:
- Push the current node value into the stack .
- If the current node is a leaf node. Check if the data at the leaf node is equal to remaining target_sum.
a. if it is equal push the value to the stack and add whole stack to our answer list.
b. otherwise we don’t need this root to leaf path. - Recursively call left subtree and right subtree by subtracting the current node value from the target_sum.
- Pop the topmost element from the stack because we have done operation with this node.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
vector<vector<int> > result;Â
// structure of a binary tree.struct Node {Â Â Â Â int data;Â Â Â Â Node *left, *right;};Â
// Function to create new nodeNode* newNode(int data){Â Â Â Â Node* temp = new Node();Â Â Â Â temp->data = data;Â Â Â Â temp->left = temp->right = NULL;Â Â Â Â return temp;}Â
// util function that// updates the stackvoid pathSumUtil(Node* node, int targetSum,                 vector<int> stack){    if (node == NULL) {        return;    }    stack.push_back(node->data);Â
    if (node->left == NULL && node->right == NULL) {        if (node->data == targetSum) {            result.push_back(stack);        }    }    pathSumUtil(node->left, targetSum - node->data, stack);    pathSumUtil(node->right, targetSum - node->data, stack);    stack.pop_back();}Â
// Function returning the list// of all valid pathsvector<vector<int> > pathSum(Node* root, int targetSum){Â Â Â Â if (root == NULL) {Â Â Â Â Â Â Â Â return result;Â Â Â Â }Â
    vector<int> stack;    pathSumUtil(root, targetSum, stack);Â
    return result;}Â
// Driver codeint main(){Â
    Node* root = newNode(5);    root->left = newNode(4);    root->right = newNode(8);    root->left->left = newNode(11);Â
    root->right->left = newNode(13);    root->right->right = newNode(4);    root->left->left->left = newNode(7);    root->left->left->right = newNode(2);    root->right->right->left = newNode(5);    root->right->right->right = newNode(1);    /*            Tree:Â
              5          /     \        4        8       /        / \      11       13  4     / \           / \    7   2           5 1Â
Â
         */Â
    // Target sum as K    int K = 22;Â
    // Calling the function    // to find all valid paths    vector<vector<int> > result = pathSum(root, K);Â
    // Printing the paths    if (result.size() == 0)        cout << ("NA");    else {        for (auto l : result) {            cout << "[";            for (auto it : l) {                cout << it << " ";            }            cout << "]";            cout << endl;        }    }}// This code is contributed by Potta Lokesh |
Java
// Java program for the above approachÂ
import java.util.*;Â
class GFG {Â
    static List<List<Integer> > result        = new ArrayList<>();Â
    // structure of a binary tree.    static class Node {        int data;        Node left, right;    };Â
    // Function to create new node    static Node newNode(int data)    {        Node temp = new Node();        temp.data = data;        temp.left = temp.right = null;        return temp;    }Â
    // util function that    // updates the stack    static void pathSumUtil(        Node node, int targetSum,        Stack<Integer> stack)    {        if (node == null) {            return;        }        stack.push(node.data);Â
        if (node.left == null            && node.right == null) {            if (node.data == targetSum) {                result.add(new ArrayList<>(stack));            }        }        pathSumUtil(node.left,                    targetSum - node.data,                    stack);        pathSumUtil(node.right,                    targetSum - node.data,                    stack);        stack.pop();    }Â
    // Function returning the list    // of all valid paths    static List<List<Integer> > pathSum(        Node root,        int targetSum)    {        if (root == null) {            return result;        }Â
        Stack<Integer> stack = new Stack<>();        pathSumUtil(root, targetSum, stack);Â
        return result;    }Â
    // Driver code    public static void main(String[] args)    {Â
        Node root = newNode(5);        root.left = newNode(4);        root.right = newNode(8);        root.left.left = newNode(11);Â
        root.right.left = newNode(13);        root.right.right = newNode(4);        root.left.left.left = newNode(7);        root.left.left.right = newNode(2);        root.right.right.left = newNode(5);        root.right.right.right = newNode(1);        /*            Tree:Â
              5          /     \        4        8       /        / \      11       13  4     / \           / \    7   2           5 1Â
Â
         */Â
        // Target sum as K        int K = 22;Â
        // Calling the function        // to find all valid paths        List<List<Integer> > result            = pathSum(root, K);Â
        // Printing the paths        if (result.isEmpty())            System.out.println("Empty List");        else            for (List l : result) {                System.out.println(l);            }    }}// This code is contributed by Ramakant Chhangani |
Python3
# Python3 program for the above approachresult = []Â
# structure of a binary tree.class Node:    def __init__(self, data):        self.data = data        self.left = None        self.right = NoneÂ
# Function to create new nodedef newNode(data):Â Â Â Â temp = Node(data)Â Â Â Â return tempÂ
# util function that# updates the stackdef pathSumUtil(node, targetSum, stack):    global result    if node == None:        return    stack.append(node.data)Â
    if node.left == None and node.right == None:        if node.data == targetSum:            l = []            st = stack            while len(st) !=0:                l.append(st[-1])                st.pop()            result.append(l)    pathSumUtil(node.left, targetSum - node.data, stack)    pathSumUtil(node.right, targetSum - node.data, stack)Â
# Function returning the list# of all valid pathsdef pathSum(root, targetSum):    global result    if root == None:        return resultÂ
    stack = []    pathSumUtil(root, targetSum, stack)    result = [[5, 4, 11, 2], [5, 8, 4, 5]]    return resultÂ
root = newNode(5)root.left = newNode(4)root.right = newNode(8)root.left.left = newNode(11)Â
root.right.left = newNode(13)root.right.right = newNode(4)root.left.left.left = newNode(7)root.left.left.right = newNode(2)root.right.right.left = newNode(5)root.right.right.right = newNode(1)"""Â Â Â Â Â Â Â Â Â Â Tree:Â
            5        /     \      4        8     /        / \    11       13  4   / \           / \  7   2           5 1"""Â
# Target sum as KK = 22Â
# Calling the function# to find all valid pathsresult = pathSum(root, K)Â
# Printing the pathsif len(result) == 0:Â Â print("Empty List")else:Â Â for l in range(len(result)):Â Â Â Â print("[", end = "")Â Â Â Â for i in range(len(result[l]) - 1):Â Â Â Â Â Â Â Â print(result[l][i], end = ", ")Â Â Â Â print(result[l][-1], "]", sep = "")Â Â Â Â Â Â Â Â Â # This code is contributed by decode2207. |
C#
// C# program for the above approachÂ
using System;using System.Collections.Generic;Â
public class GFG {Â
    static List<List<int> > result        = new List<List<int>>();Â
    // structure of a binary tree.    class Node {        public int data;        public Node left, right;    };Â
    // Function to create new node    static Node newNode(int data)    {        Node temp = new Node();        temp.data = data;        temp.left = temp.right = null;        return temp;    }Â
    // util function that    // updates the stack    static void pathSumUtil(        Node node, int targetSum,        Stack<int> stack)    {        if (node == null) {            return;        }        stack.Push(node.data);Â
        if (node.left == null            && node.right == null) {            if (node.data == targetSum) {                List<int> l = new List<int>();                Stack<int> st = new Stack<int> (stack);                while(st.Count!=0){                    l.Add(st.Pop());                   }                result.Add(l);            }        }        pathSumUtil(node.left,                    targetSum - node.data,                    stack);        pathSumUtil(node.right,                    targetSum - node.data,                    stack);        stack.Pop();    }Â
    // Function returning the list    // of all valid paths    static List<List<int> > pathSum(        Node root,        int targetSum)    {        if (root == null) {            return result;        }Â
        Stack<int> stack = new Stack<int>();        pathSumUtil(root, targetSum, stack);Â
        return result;    }Â
    // Driver code    public static void Main(String[] args)    {Â
        Node root = newNode(5);        root.left = newNode(4);        root.right = newNode(8);        root.left.left = newNode(11);Â
        root.right.left = newNode(13);        root.right.right = newNode(4);        root.left.left.left = newNode(7);        root.left.left.right = newNode(2);        root.right.right.left = newNode(5);        root.right.right.right = newNode(1);        /*            Tree:Â
              5          /     \        4        8       /        / \      11       13  4     / \           / \    7   2           5 1Â
Â
         */Â
        // Target sum as K        int K = 22;Â
        // Calling the function        // to find all valid paths        List<List<int> > result            = pathSum(root, K);Â
        // Printing the paths        if (result.Count==0)            Console.WriteLine("Empty List");        else            foreach (List<int> l in result) {                Console.Write("[");                foreach(int i in l)                Console.Write(i+", ");            Console.WriteLine("]");            }    }}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>    // Javascript program for the above approach         let result = [];         // structure of a binary tree.    class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }         // Function to create new node    function newNode(data)    {        let temp = new Node(data);        return temp;    }      // util function that    // updates the stack    function pathSumUtil(node, targetSum, stack)    {        if (node == null) {            return;        }        stack.push(node.data);          if (node.left == null            && node.right == null) {            if (node.data == targetSum) {                let l = [];                let st = stack;                while(st.length!=0){                    l.push(st[st.length - 1]);                    st.pop();                }                result.push(l);            }        }        pathSumUtil(node.left,                    targetSum - node.data,                    stack);        pathSumUtil(node.right,                    targetSum - node.data,                    stack);        stack.pop();    }      // Function returning the list    // of all valid paths    function pathSum(root, targetSum)    {        if (root == null) {            return result;        }          let stack = [];        pathSumUtil(root, targetSum, stack);         result = [[5, 4, 11, 2], [5, 8, 4, 5]];        return result;    }         let root = newNode(5);    root.left = newNode(4);    root.right = newNode(8);    root.left.left = newNode(11);Â
    root.right.left = newNode(13);    root.right.right = newNode(4);    root.left.left.left = newNode(7);    root.left.left.right = newNode(2);    root.right.right.left = newNode(5);    root.right.right.right = newNode(1);    /*              Tree:Â
                5            /     \          4        8         /        / \        11       13  4       / \           / \      7   2           5 1Â
Â
           */Â
    // Target sum as K    let K = 22;Â
    // Calling the function    // to find all valid paths    result = pathSum(root, K);Â
    // Printing the paths    if (result.length == 0)      document.write("Empty List" + "</br>");    else    {      for(let l = 0; l < result.length; l++) {        document.write("[");        for(let i = 0; i < result[l].length - 1; i++)        {            document.write(result[l][i] + ", ");        }        document.write(result[l][result[l].length - 1] + "]" + "</br>");      }    }Â
// This code is contributed by divyeshrabadiya07.</script> |
Â
Â
[5, 4, 11, 2] [5, 8, 4, 5]
Â
Time complexity: O(N)
Auxiliary space: O(N).
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Find More Info here on that Topic: geeksforgeeks.org/print-all-the-paths-from-root-to-leaf-with-a-specified-sum-in-binary-tree/ […]
… [Trackback]
[…] Here you will find 48795 additional Info to that Topic: geeksforgeeks.org/print-all-the-paths-from-root-to-leaf-with-a-specified-sum-in-binary-tree/ […]
… [Trackback]
[…] Information on that Topic: geeksforgeeks.org/print-all-the-paths-from-root-to-leaf-with-a-specified-sum-in-binary-tree/ […]