Open In App

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

Last Updated : 07 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary tree and target sum, the task is to find all the possible paths from root to leaf that have the sum equal to the given sum.

Examples

Input:

2

Output: [[10, 28]]
Explanation: Paths [[10, 28]] sum to 38.

Input:

1

Output: []
Explanation: No root-to-leaf path sums to 8, so the output is empty.

Approach:

The idea is to traverse the binary tree using DFS traversal from the root to all the leaf nodes, keeping track of the current path and the remaining sum. For each node, subtract its value from the target sum and continue the search in the left and right subtrees. When a leaf node is reached and the sum is zero, the path is valid and is stored.

C++
// C++ Program to print all Root to Leaf paths
// with a sum equal to a given number
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    Node *left, *right;
    int data;

    Node(int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Helper function to find paths with the given sum
void findPaths(Node* root, int sum, vector<int>& path, 
               vector<vector<int>>& result) {
    if (root == nullptr) {
        return;
    }

    // Add current node's data to the path
    path.push_back(root->data);

    // Check if the current node is a leaf and 
    // sum equals its value
    if (root->left == nullptr && root->right == nullptr 
        && sum == root->data) {
        result.push_back(path);
    }
    else {
      
        // Otherwise, check in the left and 
        // right subtrees
        findPaths(root->left, 
                   sum - root->data, path, result);
      
        findPaths(root->right, 
                   sum - root->data, path, result);
    }

    // Backtrack to explore other paths
    path.pop_back();
}

// Function to find and return all paths 
// with the given sum
vector<vector<int>> PathsWithSum(Node* root, 
                                   int sum) {
    vector<int> path;
    vector<vector<int>> result;
    findPaths(root, sum, path, result);
    return result;
}

void print2DArray(vector<vector<int>>& arr) {
    for (auto& row : arr) {
        for (int val : row) {
            cout << val << " ";
        }
        cout << endl;
    }
}

int main() {

    // Constructed binary tree is
    //        10
    //       /  \
    //      1    2
    //     / \    \
    //    4   5    3 
    Node* root = new Node(10);
    root->left = new Node(1);
    root->right = new Node(2);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->right->right = new Node(3);
  
    int sum = 15;
    vector<vector<int>> paths 
         = PathsWithSum(root, sum);
   
    print2DArray(paths);

    return 0;
}
Java
// Java Program to print all Root to Leaf paths
// with a sum equal to a given number
import java.util.*;

class Node {
    Node left, right;
    int data;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Helper function to find paths with the given sum
    static void findPaths(Node root, int sum, List<Integer> path, 
                          List<List<Integer>> result) {
        if (root == null) {
            return;
        }

        // Add current node's data to the path
        path.add(root.data);

        // Check if the current node is a leaf and 
        // sum equals its value
        if (root.left == null && root.right == null 
            && sum == root.data) {
            result.add(new ArrayList<>(path));
        } 
        else {

            // Otherwise, check in the left and 
            // right subtrees
            findPaths(root.left, sum - root.data, path, result);
            findPaths(root.right, sum - root.data, path, result);
        }

        // Backtrack to explore other paths
        path.remove(path.size() - 1);
    }

    // Function to find and return all paths 
    // with the given sum
    static List<List<Integer>> PathsWithSum(Node root, int sum) {
        List<Integer> path = new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
        findPaths(root, sum, path, result);
        return result;
    }

    static void print2DArray(List<List<Integer>> arr) {
        for (List<Integer> row : arr) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {

        // Constructed binary tree is
        //        10
        //       /  \
        //      1    2
        //     / \    \
        //    4   5    3 
        Node root = new Node(10);
        root.left = new Node(1);
        root.right = new Node(2);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.right = new Node(3);

        int sum = 15;
        List<List<Integer>> paths
               = PathsWithSum(root, sum);

        print2DArray(paths);
    }
}
Python
# Python program to print all Root to Leaf paths
# with a sum equal to a given number
class Node:
     def __init__(self, data):
      self.data = data
      self.left = None
      self.right = None

# Helper function to find paths with the given sum
def findPaths(root, sum, path, result):
    if root is None:
        return

    # Add current node's data to the path
    path.append(root.data)

    # Check if the current node is a leaf and 
    # sum equals its value
    if root.left is None and root.right \
                is None and sum == root.data:
      
        result.append(list(path))
    else:
      
        # Otherwise, check in the left and 
        # right subtrees
        findPaths(root.left, sum - root.data, path, result)
        findPaths(root.right, sum - root.data, path, result)

    # Backtrack to explore other paths
    path.pop()

# Function to find and return all paths with the given sum
def pathsWithSum(root, sum):
    path = []
    result = []
    findPaths(root, sum, path, result)
    return result

def print2DArray(arr):
    for row in arr:
        print(" ".join(map(str, row)))

if __name__ == "__main__":

    # Constructed binary tree is
    #        10
    #       /  \
    #      1    2
    #     / \    \
    #    4   5    3 
    root = Node(10)
    root.left = Node(1)
    root.right = Node(2)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.right = Node(3)

    sum = 15
    paths = pathsWithSum(root, sum)

    print2DArray(paths)
C#
// C# Program to print all Root to Leaf paths
// with a sum equal to a given number
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Helper function to find paths with the given sum
    static void FindPaths(Node root, int sum, 
                                 List<int> path, 
                                 List<List<int>> result) {
        if (root == null) {
            return;
        }

        // Add current node's data to the path
        path.Add(root.data);

        // Check if the current node is a leaf and 
        // sum equals its value
        if (root.left == null && root.right == null 
            && sum == root.data) {
            result.Add(new List<int>(path));
        } 
        else {

            // Otherwise, check in the left and 
            // right subtrees
            FindPaths(root.left, sum - root.data, path, result);
            FindPaths(root.right, sum - root.data, path, result);
        }

        // Backtrack to explore other paths
        path.RemoveAt(path.Count - 1);
    }

    // Function to find and return all paths 
    // with the given sum
    static List<List<int>> PathsWithSum(Node root, int sum) {
        List<int> path = new List<int>();
        List<List<int>> result = new List<List<int>>();
        FindPaths(root, sum, path, result);
        return result;
    }

    static void Print2DArray(List<List<int>> arr) {
        foreach (var row in arr) {
            foreach (int val in row) {
                Console.Write(val + " ");
            }
            Console.WriteLine();
        }
    }

    static void Main(string[] args) {

        // Constructed binary tree is
        //        10
        //       /  \
        //      1    2
        //     / \    \
        //    4   5    3 
        Node root = new Node(10);
        root.left = new Node(1);
        root.right = new Node(2);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.right = new Node(3);

        int sum = 15;
        List<List<int>> paths 
             = PathsWithSum(root, sum);

        Print2DArray(paths);
    }
}
JavaScript
// JavaScript program to print all Root to Leaf paths
// with a sum equal to a given number
class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

// Helper function to find paths with the given sum
function findPaths(root, sum, path, result) {
    if (root === null) {
        return;
    }

    // Add current node's data to the path
    path.push(root.data);

    // Check if the current node is a leaf and
    // sum equals its value
    if (root.left === null && root.right === null 
                         && sum === root.data) {
                         
        result.push([...path]);
    } 
    else {
    
        // Otherwise, check in the left and
        // right subtrees
        findPaths(root.left, sum - root.data, path, result);
        findPaths(root.right, sum - root.data, path, result);
    }

    // Backtrack to explore other paths
    path.pop();
}

// Function to find and return all paths 
// with the given sum
function pathsWithSum(root, sum) {
    let path = [];
    let result = [];
    findPaths(root, sum, path, result);
    return result;
}

function print2DArray(arr) {
    arr.forEach(row => {
        console.log(row.join(" "));
    });
}

// Constructed binary tree is
//        10
//       /  \
//      1    2
//     / \    \
//    4   5    3
let root = new Node(10);
root.left = new Node(1);
root.right = new Node(2);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.right = new Node(3);

let sum = 15;
let paths = pathsWithSum(root, sum);

print2DArray(paths);

Output
10 1 4 
10 2 3 

Time Complexity: O(n), where n is the number of nodes in the tree, as each node is visited once.
Auxiliary Space: O(h), where h is the height of the tree, due to the recursion stack and path storage.



Next Article
Article Tags :
Practice Tags :

Similar Reads