The Wayback Machine - https://web.archive.org/web/20240624043923/https://www.geeksforgeeks.org/print-all-root-to-leaf-paths-of-an-n-ary-tree/
Open In App

Print all root to leaf paths of an N-ary tree

Last Updated : 18 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an N-Ary tree, the task is to print all root to leaf paths of the given N-ary Tree.

Examples:

Input:
                        1
                      /   \
                   2      3
                 /      /   \
              4      5     6
                           /   \
                        7      8

Output:
1 2 4
1 3 5
1 3 6 7
1 3 6 8

Input:
                          1
                        / | \
                      2  5  3
                    / \        \
                   4   5       6
Output:
1 2 4
1 2 5
1 5
1 3 6

Approach: The idea to solve this problem is to start traversing the N-ary tree using depth-first search and keep inserting every node encountered in a vector until a leaf node is encountered. Whenever a leaf node is encountered, print the elements stored in the vector as the current root-to-leaf path traversed and remove the last added leaf and check for the next combination.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of an N ary tree node
class Node {
public:
    int data;
    vector<Node*> child;
 
    // Parameterized Constructor
    Node(int x)
        : data(x)
    {
    }
};
 
// Function to print the root to leaf
// path of the given N-ary Tree
void printPath(vector<int> vec)
{
    // Print elements in the vector
    for (int ele : vec) {
        cout << ele << " ";
    }
    cout << endl;
}
 
// Utility function to print all
// root to leaf paths of N-ary Tree
void printAllRootToLeafPaths(
    Node* root, vector<int> vec)
{
    // If root is null
    if (!root)
        return;
 
    // Insert current node's
    // data into the vector
    vec.push_back(root->data);
 
    // If current node is a leaf node
    if (root->child.empty()) {
 
        // Print the path
        printPath(vec);
 
        // Pop the leaf node
        // and return
        vec.pop_back();
        return;
    }
 
    // Recur for all children of
    // the current node
    for (int i = 0;
        i < root->child.size(); i++)
 
        // Recursive Function Call
        printAllRootToLeafPaths(
            root->child[i], vec);
}
 
// Function to print root to leaf path
void printAllRootToLeafPaths(Node* root)
{
    // If root is null, return
    if (!root)
        return;
 
    // Stores the root to leaf path
    vector<int> vec;
 
    // Utility function call
    printAllRootToLeafPaths(root, vec);
}
 
// Driver Code
int main()
{
    // Given N-Ary tree
    Node* root = new Node(1);
    (root->child).push_back(new Node(2));
    (root->child).push_back(new Node(3));
    (root->child[0]->child).push_back(new Node(4));
    (root->child[1]->child).push_back(new Node(5));
    (root->child[1]->child).push_back(new Node(6));
    (root->child[1]->child[1]->child)
        .push_back(new Node(7));
    (root->child[1]->child[1]->child)
        .push_back(new Node(8));
 
    // Function Call
    printAllRootToLeafPaths(root);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.ArrayList;
class GFG
{
 
    // Structure of an N ary tree node
    static class Node
    {
        int data;
        ArrayList<Node> child;
 
        // Parameterized Constructor
        public Node(int x)
        {
            this.data = x;
            this.child = new ArrayList<>();
        }
    };
 
    // Function to print the root to leaf
    // path of the given N-ary Tree
    static void printPath(ArrayList<Integer> vec)
    {
       
        // Print elements in the vector
        for (int ele : vec)
        {
            System.out.print(ele + " ");
        }
        System.out.println();
    }
 
    // Utility function to print all
    // root to leaf paths of an Nary Tree
    static void printAllRootToLeafPaths(Node root, ArrayList<Integer> vec)
    {
       
        // If root is null
        if (root == null)
            return;
 
        // Insert current node's
        // data into the vector
        vec.add(root.data);
 
        // If current node is a leaf node
        if (root.child.isEmpty())
        {
 
            // Print the path
            printPath(vec);
 
            // Pop the leaf node
            // and return
            vec.remove(vec.size() - 1);
            return;
        }
 
        // Recur for all children of
        // the current node
        for (int i = 0; i < root.child.size(); i++)
 
            // Recursive Function Call
            printAllRootToLeafPaths(root.child.get(i), vec);
        vec.remove(vec.size() - 1);
    }
 
    // Function to print root to leaf path
    static void printAllRootToLeafPaths(Node root)
    {
       
        // If root is null, return
        if (root == null)
            return;
 
        // Stores the root to leaf path
        ArrayList<Integer> vec = new ArrayList<>();
 
        // Utility function call
        printAllRootToLeafPaths(root, vec);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given N-Ary tree
        Node root = new Node(1);
        (root.child).add(new Node(2));
        (root.child).add(new Node(3));
        (root.child.get(0).child).add(new Node(4));
        (root.child.get(1).child).add(new Node(5));
        (root.child.get(1).child).add(new Node(6));
        (root.child.get(1).child.get(1).child).add(new Node(7));
        (root.child.get(1).child.get(1).child).add(new Node(8));
 
        // Function Call
        printAllRootToLeafPaths(root);
    }
}
 
// This code is contributed by sanjeev2552


Python3




# Python3 program for the above approach
 
# Structure of an N ary tree node
class Node:
     
    def __init__(self, x):
         
        self.data = x
        self.child = []
 
# Function to print the root to leaf
# path of the given N-ary Tree
def printPath(vec):
     
    # Print elements in the vector
    for ele in vec:
        print(ele, end = " ")
         
    print()
 
# Utility function to print all
# root to leaf paths of an Nary Tree
def printAllRootToLeafPaths(root):
     
    global vec
     
    # If root is null
    if (not root):
        return
 
    # Insert current node's
    # data into the vector
    vec.append(root.data)
 
    # If current node is a leaf node
    if (len(root.child) == 0):
 
        # Print the path
        printPath(vec)
 
        # Pop the leaf node
        # and return
        vec.pop()
        return
 
    # Recur for all children of
    # the current node
    for i in range(len(root.child)):
 
        # Recursive Function Call
        printAllRootToLeafPaths(root.child[i])
         
    vec.pop()   
 
# Function to print root to leaf path
def printRootToLeafPaths(root):
     
    global vec
     
    # If root is null, return
    if (not root):
        return
 
    # Utility function call
    printAllRootToLeafPaths(root)
 
# Driver Code
if __name__ == '__main__':
     
    # Given N-Ary tree
    vec = []
    root = Node(1)
    root.child.append(Node(2))
    root.child.append(Node(3))
    root.child[0].child.append(Node(4))
    root.child[1].child.append(Node(5))
    root.child[1].child.append(Node(6))
    root.child[1].child[1].child.append(Node(7))
    root.child[1].child[1].child.append(Node(8))
 
    # Function Call
    printRootToLeafPaths(root)
 
# This code is contributed by mohit kumar 29


C#




using System;
using System.Collections.Generic;
 
// Structure of an N ary tree node
public class Node
{
    public int data;
    public List<Node> child;
  
    // Parameterized Constructor
    public Node(int x)
    {
        this.data = x;
        this.child = new List<Node>();
    }
}
 
public class GFG
{
     
    // Function to print the root to leaf
    // path of the given N-ary Tree
    static void printPath(List<int> vec)
    {
        
        // Print elements in the vector
        foreach (int ele in vec)
        {
            Console.Write(ele + " ");
        }
        Console.WriteLine();
    }
     
    // Utility function to print all
    // root to leaf paths of an Nary Tree
    static void printAllRootToLeafPaths(Node root, List<int> vec)
    {
       
        // If root is null
        if (root == null)
            return;
  
        // Insert current node's
        // data into the vector
        vec.Add(root.data);
         
        // If current node is a leaf node
        if (root.child.Count == 0)
        {
           
            // Print the path
            printPath(vec);
  
            // Pop the leaf node
            // and return
            vec.RemoveAt(vec.Count - 1);
            return;
        }
         
        // Recur for all children of
        // the current node
        for (int i = 0; i < root.child.Count; i++)
        {
            // Recursive Function Call
            printAllRootToLeafPaths(root.child[i], vec);
        }
        vec.RemoveAt(vec.Count - 1);
    }
     
    // Function to print root to leaf path
    static void printAllRootToLeafPaths(Node root)
    {
        
        // If root is null, return
        if (root == null)
            return;
  
        // Stores the root to leaf path
        List<int> vec = new List<int>();
  
        // Utility function call
        printAllRootToLeafPaths(root, vec);
    }
     
    // Driver Code
    static public void Main ()
    {
       
        // Given N-Ary tree
        Node root = new Node(1);
        (root.child).Add(new Node(2));
        (root.child).Add(new Node(3));
        (root.child[0].child).Add(new Node(4));
        (root.child[1].child).Add(new Node(5));
        (root.child[1].child).Add(new Node(6));
        (root.child[1].child[1].child).Add(new Node(7));
        (root.child[1].child[1].child).Add(new Node(8));
         
        // Function Call
        printAllRootToLeafPaths(root);
    }
}
 
// This code is contributed by rag2127


Javascript




<script>
// Javascript program for the above approach
 
// Structure of an N ary tree node
class Node
{
    constructor(x)
    {
        this.data = x;
            this.child = [];
    }
}
 
// Function to print the root to leaf
    // path of the given N-ary Tree
function  printPath(vec)
{
    // Print elements in the vector
        for (let ele=0;ele< vec.length;ele++)
        {
            document.write(vec[ele] + " ");
        }
        document.write("<br>");
}
 
// Utility function to print all
    // root to leaf paths of an Nary Tree
function printAllRootToLeafPaths(root,vec)
{
    // If root is null
        if (root == null)
            return;
  
        // Insert current node's
        // data into the vector
        vec.push(root.data);
  
        // If current node is a leaf node
        if (root.child.length==0)
        {
  
            // Print the path
            printPath(vec);
  
            // Pop the leaf node
            // and return
            vec.pop();
            return;
        }
  
        // Recur for all children of
        // the current node
        for (let i = 0; i < root.child.length; i++)
  
            // Recursive Function Call
            printAllRootToLeafPaths(root.child[i], vec);
        vec.pop();
}
 
// Function to print root to leaf path
function printAllRootToLeaf_Paths(root)
{
    // If root is null, return
        if (root == null)
            return;
  
        // Stores the root to leaf path
        let vec = [];
  
        // Utility function call
        printAllRootToLeafPaths(root, vec);
}
 
// Driver Code
let root = new Node(1);
(root.child).push(new Node(2));
(root.child).push(new Node(3));
(root.child[0].child).push(new Node(4));
(root.child[1].child).push(new Node(5));
(root.child[1].child).push(new Node(6));
(root.child[1].child[1].child).push(new Node(7));
(root.child[1].child[1].child).push(new Node(8));
 
// Function Call
printAllRootToLeaf_Paths(root);
 
// This code is contributed by unknown2108
</script>


Output: 

1 2 4 
1 3 5 
1 3 6 7 
1 3 6 8

 

Time Complexity: O(N)
Space Complexity: O(N)



Previous Article
Next Article

Similar Reads

Given a binary tree, print out all of its root-to-leaf paths one per line.
Given the roots of a tree. print out all of its root-to-leaf paths one per line.. Algorithm: initialize: pathlen = 0, path[1000] /*1000 is some max limit for paths, it can change*/ /*printPathsRecur traverses nodes of tree in preorder */ printPathsRecur(tree, path[], pathlen) 1) If node is not NULL then a) push data to path array: path[pathlen] = n
9 min read
Print all the root-to-leaf paths of a Binary Tree whose XOR is non-zero
Given a Binary Tree, the task is to print all root-to-leaf paths of this tree whose xor value is non-zero. Examples: Input: 10 / \ 10 3 / \ 10 3 / \ / \ 7 3 42 13 / 7 Output: 10 3 10 7 10 3 3 42 Explanation: All the paths in the given binary tree are : {10, 10} xor value of the path is = 10 ^ 10 = 0 {10, 3, 10, 7} xor value of the path is = 10 ^ 3
11 min read
Print all the paths from root to leaf, with a specified sum in Binary tree
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
9 min read
Given a binary tree, print all root-to-leaf paths
For the below example tree, all root-to-leaf paths are: 10 –&gt; 8 –&gt; 3 10 –&gt; 8 –&gt; 5 10 –&gt; 2 –&gt; 2 Recommended PracticeRoot to Leaf PathsTry It! Algorithm: Use a path array path[] to store current root to leaf path. Traverse from root to all leaves in top-down fashion. While traversing, store data of all nodes in current path in array
15+ min read
Print all root-to-leaf paths with maximum count of even nodes
Given a Binary tree, the task is to print all possible root-to-leaf paths having a maximum number of even valued nodes. Examples: Input: 2 / \ 6 3 / \ \ 4 7 11 / \ \ 10 12 1 Output: 2 -&gt; 6 -&gt; 4 -&gt; 10 2 -&gt; 6 -&gt; 4 -&gt; 12 Explanation: Count of even nodes on the path 2 -&gt; 6 -&gt; 4 -&gt; 10 = 4 Count of even nodes on the path 2 -
13 min read
Print all root to leaf paths with there relative positions
Given a binary tree, print the root to the leaf path, but add "_" to indicate the relative position. Example: Input : Root of below tree A / \ B C / \ / \ D E F G Output : All root to leaf paths _ _ A _ B D _ A B _ E A _ C F A _ C _ _ G Asked In: Google Interview The idea base on print path in vertical order. Below is complete algorithm : We do Pre
11 min read
Remove nodes from Binary Tree such that sum of all remaining root-to-leaf paths is atleast K
Given a Binary Tree and an integer K, the task is to delete nodes from the given Tree such that the sum of all nodes of all remaining root to leaf paths is at least K. Examples: Input: K = 27 Output: 5 4 8 5 6 11Explanation:Below are the paths whose sum is less than 27: 5 -&gt; 3 -&gt; 9: Path Sum = 5 + 3 + 9 = 17.5 -&gt; 4 -&gt; 9: Path Sum = 5 +
11 min read
GCD from root to leaf path in an N-ary tree
Given an N-ary tree and an array val[] which stores the values associated with all the nodes. Also given are a leaf node X and N integers which denotes the value of the node. The task is to find the gcd of all the numbers in the node in the path between leaf to the root. Examples: Input: 1 / \ 2 3 / / \ 4 5 6 / \ 7 8 val[] = { -1, 6, 2, 6, 3, 4, 12
7 min read
Maximize sum of path from the Root to a Leaf node in N-ary Tree
Given a generic tree consisting of N nodes, the task is to find the maximum sum of the path from the root to the leaf node. Examples: Input: Output: 12Explanation: The path sum to every leaf from the root are:For node 4: 1 -&gt; 2 -&gt; 4 = 7For node 5: 1 -&gt; 2 -&gt; 5 = 8For node 6: 1 -&gt; 3 -&gt; 6 = 10For node 7: 1 -&gt; 3 -&gt; 7 = 11For nod
6 min read
Print all leaf nodes of an n-ary tree using DFS
Given an array edge[][2] where (edge[i][0], edge[i][1]) defines an edge in the n-ary tree, the task is to print all the leaf nodes of the given tree using. Examples: Input: edge[][] = {{1, 2}, {1, 3}, {2, 4}, {2, 5}, {3, 6}} Output: 4 5 6 1 / \ 2 3 / \ \ 4 5 6 Input: edge[][] = {{1, 5}, {1, 7}, {5, 6}} Output: 6 7 Approach: DFS can be used to trave
7 min read
three90RightbarBannerImg