Print RoottoLeaf Paths in a Binary Tree (original) (raw)

Last Updated : 23 Jul, 2025

Given a Binary Tree of nodes, the task is to find all the possible paths from the root node to all the **leaf nodes of the binary tree.
**Note: The paths should be returned such that paths from the left subtree of any node are listed first, followed by paths from the right subtree.

**Example:

**Input: root[] = [1, 2, 3, 4, 5, N, N]
ex-3**Output: [[1, 2, 4], [1, 2, 5], [1, 3]]
**Explanation: All the possible paths from root node to leaf nodes are: 1 -> 2 -> 4, 1 -> 2 -> 5 and 1 -> 3

Try It Yourselfredirect icon

Approach: Recursion with Backtracking

The approach involves the use **recursion to traverse the given Binary tree. The **recursive function will append **node values to a **path as it **navigates down the tree. After reaching a **leaf node, the path is stored in the final **result. After exploring both **left and **right subtrees, the function **backtracks to explore alternate paths.

C++ `

// C++ code of print all paths from root node // to leaf node using recursion. #include #include using namespace std;

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

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

};

void collectPaths(Node *node, vector &path, vector<vector> &paths) { if (node == nullptr) return;

// Append this node to the path
path.push_back(node->data);

// If it's a leaf node, store the path
if (node->left == nullptr && node->right == nullptr)
{
    paths.push_back(path);
}
else
{

    // Otherwise, try both subtrees
    collectPaths(node->left, path, paths);
    collectPaths(node->right, path, paths);
}

// Backtrack: remove the last element
// from the path
path.pop_back();

}

// Function to get all paths from root to leaf vector<vector> Paths(Node *root) { vector<vector> paths; vector path; collectPaths(root, path, paths); return paths; }

int main(){

Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);

vector<vector<int>> res = Paths(root);
for (auto &row : res){
    
    for (int val : row){
    
        cout << val << " ";
    }
    cout << endl;
}

return 0;

}

Java

// Java code of print all paths from root node // to leaf node using recursion. import java.util.ArrayList;

class Node { int data; Node left, right;

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

}

class GfG {

// Utility function to collect all root-to-leaf paths
static void collectPaths(Node node, ArrayList<Integer> path,
                         ArrayList<ArrayList<Integer>> paths) {
    if (node == null)
        return;

    // Append this node to the path
    path.add(node.data);

    // If it's a leaf node, store the path
    if (node.left == null && node.right == null) {
        paths.add(new ArrayList<>(path));
    }
    else {
        // Otherwise, try both subtrees
        collectPaths(node.left, path, paths);
        collectPaths(node.right, path, paths);
    }

    // Backtrack: remove the last element
    // from the path
    path.remove(path.size() - 1);
}

// Function to get all paths from root to leaf
static ArrayList<ArrayList<Integer>> Paths(Node root) {
    ArrayList<ArrayList<Integer>> paths = new ArrayList<>();
    ArrayList<Integer> path = new ArrayList<>();
    collectPaths(root, path, paths);
    return paths;
}

public static void main(String[] args) {

    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.left = new Node(4);
    root.left.right = new Node(5);

    ArrayList<ArrayList<Integer>> res = Paths(root);

    for (ArrayList<Integer> row : res) {
        for (int val : row) {
            System.out.print(val + " ");
        }
        System.out.println();
    }
}

}

Python

Python code of print all paths from root node

to leaf node using recursion.

class Node: def init(self, x): self.data = x self.left = None self.right = None

Utility function to collect all root-to-leaf paths

def collectPaths(node, path, paths): if node is None: return

# Append this node to the path
path.append(node.data)

# If it's a leaf node, store the path
if node.left is None and node.right is None:
    paths.append(list(path))
else:
    # Otherwise, try both subtrees
    collectPaths(node.left, path, paths)
    collectPaths(node.right, path, paths)

# Backtrack: remove the last element
# from the path
path.pop()

Function to get all paths from root to leaf

def Paths(root): paths = [] path = [] collectPaths(root, path, paths) return paths

if name == "main":

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

res = Paths(root)

for row in res:
    for val in row:
        print(val, end=" ")
    print()

C#

// C# code of print all paths from root node // to leaf node using recursion. using System; using System.Collections.Generic;

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

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

}

class GfG {

// Utility function to collect all root-to-leaf paths
static void collectPaths(Node node, List<int> path,
                         List<List<int>> paths) {
    if (node == null)
        return;

    // Append this node to the path
    path.Add(node.data);

    // If it's a leaf node, store the path
    if (node.left == null && node.right == null) {
        paths.Add(new List<int>(path));
    }
    else {
        // Otherwise, try both subtrees
        collectPaths(node.left, path, paths);
        collectPaths(node.right, path, paths);
    }

    // Backtrack: remove the last element
    // from the path
    path.RemoveAt(path.Count - 1);
}

// Function to get all paths from root to leaf
static List<List<int>> Paths(Node root) {
    List<List<int>> paths = new List<List<int>>();
    List<int> path = new List<int>();
    collectPaths(root, path, paths);
    return paths;
}


static void Main() {
    
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.left = new Node(4);
    root.left.right = new Node(5);

    List<List<int>> res = Paths(root);
    
    foreach (var row in res) {
        foreach (int val in row) {
            Console.Write(val + " ");
        }
        Console.WriteLine();
    }
}

}

JavaScript

// JavaScript code of print all paths from root node // to leaf node using recursion.

class Node { constructor(x) { this.data = x; this.left = null; this.right = null; } }

// Utility function to collect all root-to-leaf paths function collectPaths(node, path, paths) { if (node === null) return;

// Append this node to the path
path.push(node.data);

// If it's a leaf node, store the path
if (node.left === null && node.right === null) {
    paths.push([...path]);
}
else {
    // Otherwise, try both subtrees
    collectPaths(node.left, path, paths);
    collectPaths(node.right, path, paths);
}

// Backtrack: remove the last element
// from the path
path.pop();

}

// Function to get all paths from root to leaf function Paths(root) { const paths = []; const path = []; collectPaths(root, path, paths); return paths; }

const root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5);

const res = Paths(root); for (const row of res) { console.log(row.join(" ")); }

`

**Time Complexity: O(n + L × h),where n is the number of nodes, L is the number of leaf nodes, and h is the height of the tree, since each node is visited once and each root-to-leaf path (up to length h) is copied at most once.
**Auxiliary Space: O(h), where **h is the height of tree.

**Related articles: