The Wayback Machine - https://web.archive.org/web/20250427030813/https://www.geeksforgeeks.org/given-a-binary-tree-print-all-root-to-leaf-paths/
Open In App

Print Root-to-Leaf Paths in a Binary Tree Using Recursion

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

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.

Example:

Input:

ex-3

Output:

1 2 4
1 2 5
1 3

Approach:

The approach involves using recursion to traverse a 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.

Below is the implementation of the above approach: 

C++
// C++ code of print all paths from root node
// to leaf node using recursion.
#include <iostream>
#include <vector>
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<int> &path, 
                  vector<vector<int>> &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<int>> Paths(Node *root) {
    vector<vector<int>> paths;
    vector<int> path;
    collectPaths(root, path, paths);
    return paths;
}

int main() {

    // Constructed binary tree is
    //        10
    //       /   \ 
    //      8     2
    //     / \   /
    //    3   5 2
    Node *root = new Node(10);
    root->left = new Node(8);
    root->right = new Node(2);
    root->left->left = new Node(3);
    root->left->right = new Node(5);
    root->right->left = new Node(2);

    vector<vector<int>> paths = Paths(root);
  
    for (const auto &path : paths) {
        for (int nodeValue : path) {
            cout << nodeValue << " ";
        }
      	cout << endl;
    }

    return 0;
}
Java
// Java code to print all paths from root 
// node to leaf node using recursion.
import java.util.ArrayList;
import java.util.List;

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

class GfG {

    static void collectPaths(Node node, List<Integer> path, 
                             List<List<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 List<List<Integer>> Paths(Node root) {
        List<List<Integer>> paths = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        collectPaths(root, path, paths);
        return paths;
    }
  
    public static void main(String[] args) {
      
        // Constructed binary tree is 
        //        10 
        //       /   \ 
        //      8     2 
        //     / \   /
        //    3   5 2 
        Node root = new Node(10);
        root.left = new Node(8);
        root.right = new Node(2);
        root.left.left = new Node(3);
        root.left.right = new Node(5);
        root.right.left = new Node(2);

        List<List<Integer>> paths = Paths(root);
        for (List<Integer> path : paths) {
            for (int nodeValue : path) {
                System.out.print(nodeValue + " ");
            }
            System.out.println();
        }
    }
}
Python
# Python code to 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

# Function to collect paths 
def collect_paths(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
        collect_paths(node.left, path, paths)
        collect_paths(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 = []
    collect_paths(root, [], paths)
    return paths

if __name__ == "__main__":
  
    # Constructed binary tree is 
    #        10 
    #       /   \ 
    #      8     2 
    #     / \   /
    #    3   5 2 
    root = Node(10)
    root.left = Node(8)
    root.right = Node(2)
    root.left.left = Node(3)
    root.left.right = Node(5)
    root.right.left = Node(2)

    paths = paths(root)
    for path in paths:
        print(" ".join(map(str, path)))
C#
// C# code to 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 {
  
    // Function to collect 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() {
      
        // Constructed binary tree is 
        //        10 
        //       /   \ 
        //      8     2 
        //     / \   /
        //    3   5 2 
        Node root = new Node(10);
        root.left = new Node(8);
        root.right = new Node(2);
        root.left.left = new Node(3);
        root.left.right = new Node(5);
        root.right.left = new Node(2);

        List<List<int>> paths = Paths(root);
      
		foreach (var path in paths) {
            Console.WriteLine(string.Join(" ", path));
        }
    }
}
JavaScript
// JavaScript code to print all paths from 
// root node to leaf node using recursion.

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

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 pathsArray = [];
    collectPaths(root, [], pathsArray);
    return pathsArray;
}

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

const allPaths = paths(root);
allPaths.forEach(path => {
        console.log(path.join(' '));
    });

Output
10 8 3 
10 8 5 
10 2 2 

Time Complexity: O(n), where n is the number of nodes in tree.
Auxiliary Space: O(h), where h is the height of tree.

Related articles:



Next Article
Article Tags :
Practice Tags :

Similar Reads