Paths from Root with a Sum in Binary tree

Last Updated : 9 May, 2026

Given a Binary tree and a sum, the task is to return all the paths, starting from root, that sums upto the given sum.
Note: This problem is different from root to leaf paths. Here path doesn't need to end on a leaf node.

Examples:  

Input:

4

Output: [[1, 3, 4]]
Explanation: The below image shows the path starting from the root that sums upto the given sum

1


Input:

3

Output: [[10, 28], [10, 13, 15]]
Explanation: The below image shows the path starting from the root that sums upto the given sum

2
Try It Yourself
redirect icon

[Using DFS + Backtracking] - O(n²) Time and O(h) Space

We use DFS with backtracking to explore all root-to-node paths. While traversing, we maintain the current sum and path. Whenever the sum equals the target, we store that path. After exploring each node, we backtrack to explore other potential paths.

  • Start DFS traversal from root
  • Maintain a vector path and variable sum_so_far
  • Add current node value and If sum_so_far == target, store the current path
  • Recur for left and right subtrees.
  • Backtrack by removing last element from path
C++
#include <iostream>
#include <vector>
using namespace std;

// Given Node structure
class Node {
public:
    int key;
    Node *left, *right;

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

// Utility function
void printPathsUtil(Node *curr, int sum, int currSum,
                vector<int> &path, vector<vector<int>> &ans)
{
    if (curr == nullptr)
        return;

    // Add current node
    currSum += curr->key;
    path.push_back(curr->key);

    // If sum matches → store path
    if (currSum == sum) {
        ans.push_back(path);
    }

    // Recur left and right
    printPathsUtil(curr->left, sum, currSum, path, ans);
    printPathsUtil(curr->right, sum, currSum, path, ans);

    // Backtrack
    path.pop_back();
}

// Function to return all paths
vector<vector<int>> printPaths(Node* root, int sum)
{
    vector<vector<int>> ans;
    vector<int> path;

    printPathsUtil(root, sum, 0, path, ans);

    return ans;
}

// Driver code
int main()
{
    Node* root = new Node(1);
    root->left = new Node(20);
    root->right = new Node(3);
    root->right->left = new Node(4);
    root->right->right = new Node(15);
    root->right->left->left = new Node(6);

    int sum = 8;

    vector<vector<int>> result = printPaths(root, sum);
    for (auto &path : result) {
        for (int val : path) {
            cout << val << " ";
        }
        cout << endl;
    }
    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

// Given Node structure
class Node {
    public int key;
    public Node left, right;

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

// Utility function
public class Main {
    public static void printPathsUtil(Node curr, int sum, int currSum,
                                      List<Integer> path, List<List<Integer>> ans) {
        if (curr == null)
            return;

        // Add current node
        currSum += curr.key;
        path.add(curr.key);

        // If sum matches → store path
        if (currSum == sum) {
            ans.add(new ArrayList<>(path));
        }

        // Recur left and right
        printPathsUtil(curr.left, sum, currSum, path, ans);
        printPathsUtil(curr.right, sum, currSum, path, ans);

        // Backtrack
        path.remove(path.size() - 1);
    }

    // Function to return all paths
    public static List<List<Integer>> printPaths(Node root, int sum) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> path = new ArrayList<>();

        printPathsUtil(root, sum, 0, path, ans);

        return ans;
    }

    // Driver code
    public static void main(String[] args) {
        Node root = new Node(1);
        root.left = new Node(20);
        root.right = new Node(3);
        root.right.left = new Node(4);
        root.right.right = new Node(15);
        root.right.left.left = new Node(6);

        int sum = 8;

        List<List<Integer>> result = printPaths(root, sum);
        for (List<Integer> path : result) {
            for (int val : path) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}
Python
class Node:

    def __init__(self, x):
        self.key = x
        self.left = None
        self.right = None


def printPathsUtil(curr, target,
                   currSum, path, res):

    if curr is None:
        return

    # Add current node
    currSum += curr.key
    path.append(curr.key)

    # If sum matches, store path
    if currSum == target:
        res.append(path[:])

    # Recur left and right
    printPathsUtil(curr.left, target,
                   currSum, path, res)

    printPathsUtil(curr.right, target,
                   currSum, path, res)

    # Backtrack
    path.pop()


def printPaths(root, target):

    res = []
    path = []

    printPathsUtil(root, target,
                   0, path, res)

    return res


root = Node(1)
root.left = Node(20)
root.right = Node(3)
root.right.left = Node(4)
root.right.right = Node(15)
root.right.left.left = Node(6)

target = 8

res = printPaths(root, target)

for path in res:
    print(*path)
C#
using System;
using System.Collections.Generic;

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

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

class GfG
{
    static void PrintPathsUtil(Node curr,
                               int sum,
                               int currSum,
                               List<int> path,
                               List<List<int>> res)
    {
        if (curr == null)
            return;

        // Add current node
        currSum += curr.key;
        path.Add(curr.key);

        // If sum matches, store path
        if (currSum == sum)
        {
            res.Add(new List<int>(path));
        }

        // Recur left and right
        PrintPathsUtil(curr.left, sum,
                       currSum, path, res);

        PrintPathsUtil(curr.right, sum,
                       currSum, path, res);

        // Backtrack
        path.RemoveAt(path.Count - 1);
    }

    static List<List<int>> PrintPaths(Node root,
                                      int sum)
    {
        List<List<int>> res =
                new List<List<int>>();

        List<int> path = new List<int>();

        PrintPathsUtil(root, sum, 0,
                       path, res);

        return res;
    }

    static void Main()
    {
        Node root = new Node(1);
        root.left = new Node(20);
        root.right = new Node(3);
        root.right.left = new Node(4);
        root.right.right = new Node(15);
        root.right.left.left = new Node(6);

        int sum = 8;

        List<List<int>> res =
                PrintPaths(root, sum);

        foreach (List<int> path in res)
        {
            foreach (int x in path)
            {
                Console.Write(x + " ");
            }

            Console.WriteLine();
        }
    }
}
JavaScript
class Node {

    constructor(x) {
        this.key = x;
        this.left = null;
        this.right = null;
    }
}

function printPathsUtil(curr, target,
                        currSum, path, res) {

    if (curr === null)
        return;

    // Add current node
    currSum += curr.key;
    path.push(curr.key);

    // If sum matches, store path
    if (currSum === target) {
        res.push([...path]);
    }

    // Recur left and right
    printPathsUtil(curr.left, target,
                   currSum, path, res);

    printPathsUtil(curr.right, target,
                   currSum, path, res);

    // Backtrack
    path.pop();
}

function printPaths(root, target) {

    let res = [];
    let path = [];

    printPathsUtil(root, target,
                   0, path, res);

    return res;
}

let root = new Node(1);
root.left = new Node(20);
root.right = new Node(3);
root.right.left = new Node(4);
root.right.right = new Node(15);
root.right.left.left = new Node(6);

let target = 8;

let res = printPaths(root, target);

for (let path of res) {
    console.log(...path);
}

Output
1 3 4 
Comment