📌  相关文章
📜  打印N元树的所有根到叶路径

📅  最后修改于: 2021-05-24 18:44:08             🧑  作者: Mango

给定一个N-Ary树,任务是打印给定N-ary树的所有根到叶路径。

例子:

方法:解决此问题的想法是开始使用深度优先搜索遍历N元树,并不断插入向量中遇到的每个节点,直到遇到叶节点为止。每当遇到叶节点时,都将打印遍历当前根到叶路径的矢量中存储的元素,并删除最后添加的叶并检查下一个组合。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Strcuture of an N ary tree node
class Node {
public:
    int data;
    vector 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 vec)
{
    // Print elements in the vector
    for (int ele : vec) {
        cout << ele << " ";
    }
    cout << endl;
}
 
// Utility function to print all
// root to leaf paths of an Nary Tree
void printAllRootToLeafPaths(
    Node* root, vector 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 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
{
 
    // Strcuture of an N ary tree node
    static class Node
    {
        int data;
        ArrayList 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 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 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 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
 
# Strcuture 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;
 
// Strcuture of an N ary tree node
public class Node
{
    public int data;
    public List child;
  
    // Parameterized Constructor
    public Node(int x)
    {
        this.data = x;
        this.child = new List();
    }
}
 
public class GFG
{
     
    // Function to print the root to leaf
    // path of the given N-ary Tree
    static void printPath(List 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 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 vec = new List();
  
        // 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


输出:
1 2 4 
1 3 5 
1 3 6 7 
1 3 6 8

时间复杂度: O(N)
空间复杂度: O(N)