热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

普通树(每个节点可以有任意数量的子节点)级序遍历

普通树(每个节点可以有任意数量的子节点)级序遍历原文:https://www . geesforgeks . org/gener

普通树(每个节点可以有任意数量的子节点)级序遍历

原文:https://www . geesforgeks . org/generic-tree-level-order-遍历/

给定一个类属树,执行级别顺序遍历并打印其所有节点
示例:

Input : 10
/ / \ \
2 34 56 100
/ \ | / | \
77 88 1 7 8 9
Output : 10
2 34 56 100
77 88 1 7 8 9
Input : 1
/ / \ \
2 3 4 5
/ \ | / | \
6 7 8 9 10 11
Output : 1
2 3 4 5
6 7 8 9 10 11

这个问题的解决方法类似于二叉树中的级顺序遍历。我们从推送队列中的根节点开始,对于每个节点,我们弹出它,打印它,并推送它在队列中的所有子节点。
在一般树的情况下,我们将子节点存储在向量中。因此,我们将向量的所有元素放入队列中。

C++

// CPP program to do level order traversal
// of a generic tree
#include
using namespace std;
// Represents a node of an n-ary tree
struct Node
{
    int key;
    vectorchild;
};
 // Utility function to create a new tree node
Node *newNode(int key)
{
    Node *temp = new Node;
    temp->key = key;
    return temp;
}
// Prints the n-ary tree level wise
void LevelOrderTraversal(Node * root)
{
    if (root==NULL)
        return;
    // Standard level order traversal code
    // using queue
    queue q;  // Create a queue
    q.push(root); // Enqueue root
    while (!q.empty())
    {
        int n = q.size();
        // If this node has children
        while (n > 0)
        {
            // Dequeue an item from queue and print it
            Node * p = q.front();
            q.pop();
            cout <key <<" ";
            // Enqueue all children of the dequeued item
            for (int i=0; ichild.size(); i++)
                q.push(p->child[i]);
            n--;
        }
        cout <    }
}
// Driver program
int main()
{
    /*   Let us create below tree
    *              10
    *        /   /    \   \
    *        2  34    56   100
    *       / \         |   /  | \
    *      77  88       1   7  8  9
    */
    Node *root = newNode(10);
    (root->child).push_back(newNode(2));
    (root->child).push_back(newNode(34));
    (root->child).push_back(newNode(56));
    (root->child).push_back(newNode(100));
    (root->child[0]->child).push_back(newNode(77));
    (root->child[0]->child).push_back(newNode(88));
    (root->child[2]->child).push_back(newNode(1));
    (root->child[3]->child).push_back(newNode(7));
    (root->child[3]->child).push_back(newNode(8));
    (root->child[3]->child).push_back(newNode(9));
    cout <<"Level order traversal Before Mirroring\n";
    LevelOrderTraversal(root);
    return 0;
}

Java 语言(一种计算机语言,尤用于创建网站)

// Java program to do level order traversal
// of a generic tree
import java.util.*;
class GFG
{
// Represents a node of an n-ary tree
static class Node
{
    int key;
    Vectorchild = new Vector<>();
};
// Utility function to create a new tree node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.key = key;
    return temp;
}
// Prints the n-ary tree level wise
static void LevelOrderTraversal(Node root)
{
    if (root == null)
        return;
    // Standard level order traversal code
    // using queue
    Queue q = new LinkedList<>(); // Create a queue
    q.add(root); // Enqueue root
    while (!q.isEmpty())
    {
        int n = q.size();
        // If this node has children
        while (n > 0)
        {
            // Dequeue an item from queue
            // and print it
            Node p = q.peek();
            q.remove();
            System.out.print(p.key + " ");
            // Enqueue all children of
            // the dequeued item
            for (int i = 0; i                 q.add(p.child.get(i));
            n--;
        }
        // Print new line between two levels
        System.out.println();
    }
}
// Driver Code
public static void main(String[] args)
{
    /* Let us create below tree
    *             10
    *     / / \ \
    *     2 34 56 100
    *     / \         | / | \
    *     77 88     1 7 8 9
    */
    Node root = newNode(10);
    (root.child).add(newNode(2));
    (root.child).add(newNode(34));
    (root.child).add(newNode(56));
    (root.child).add(newNode(100));
    (root.child.get(0).child).add(newNode(77));
    (root.child.get(0).child).add(newNode(88));
    (root.child.get(2).child).add(newNode(1));
    (root.child.get(3).child).add(newNode(7));
    (root.child.get(3).child).add(newNode(8));
    (root.child.get(3).child).add(newNode(9));
    System.out.println("Level order traversal " +
                            "Before Mirroring ");
    LevelOrderTraversal(root);
}
}
// This code is contributed by Rajput-Ji

Python 3

# Python3 program to do level order traversal
# of a generic tree
# Represents a node of an n-ary tree
class Node:
    def __init__(self, key):
        self.key = key
        self.child = []
 # Utility function to create a new tree node
def newNode(key):   
    temp = Node(key)
    return temp
# Prints the n-ary tree level wise
def LevelOrderTraversal(root):
    if (root == None):
        return;
    # Standard level order traversal code
    # using queue
    q = []  # Create a queue
    q.append(root); # Enqueue root
    while (len(q) != 0):
        n = len(q);
        # If this node has children
        while (n > 0):
            # Dequeue an item from queue and print it
            p = q[0]
            q.pop(0);
            print(p.key, end=' ')
            # Enqueue all children of the dequeued item
            for i in range(len(p.child)):
                q.append(p.child[i]);
            n -= 1
        print() # Print new line between two levels
# Driver program
if __name__=='__main__':
    '''   Let us create below tree
                  10
            /   /    \   \
            2  34    56   100
           / \         |   /  | \
          77  88       1   7  8  9
    '''
    root = newNode(10);
    (root.child).append(newNode(2));
    (root.child).append(newNode(34));
    (root.child).append(newNode(56));
    (root.child).append(newNode(100));
    (root.child[0].child).append(newNode(77));
    (root.child[0].child).append(newNode(88));
    (root.child[2].child).append(newNode(1));
    (root.child[3].child).append(newNode(7));
    (root.child[3].child).append(newNode(8));
    (root.child[3].child).append(newNode(9));
    print("Level order traversal Before Mirroring")
    LevelOrderTraversal(root);
    # This code is contributed by rutvik_56.

C

// C# program to do level order traversal
// of a generic tree
using System;
using System.Collections.Generic;
class GFG
{
// Represents a node of an n-ary tree
public class Node
{
    public int key;
    public Listchild = new List();
};
// Utility function to create a new tree node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.key = key;
    return temp;
}
// Prints the n-ary tree level wise
static void LevelOrderTraversal(Node root)
{
    if (root == null)
        return;
    // Standard level order traversal code
    // using queue
    Queue q = new Queue(); // Create a queue
    q.Enqueue(root); // Enqueue root
    while (q.Count != 0)
    {
        int n = q.Count;
        // If this node has children
        while (n > 0)
        {
            // Dequeue an item from queue
            // and print it
            Node p = q.Peek();
            q.Dequeue();
            Console.Write(p.key + " ");
            // Enqueue all children of
            // the dequeued item
            for (int i = 0; i                 q.Enqueue(p.child[i]);
            n--;
        }
        // Print new line between two levels
        Console.WriteLine();
    }
}
// Driver Code
public static void Main(String[] args)
{
    /* Let us create below tree
    *             10
    *     / / \ \
    *     2 34 56 100
    *     / \         | / | \
    *     77 88     1 7 8 9
    */
    Node root = newNode(10);
    (root.child).Add(newNode(2));
    (root.child).Add(newNode(34));
    (root.child).Add(newNode(56));
    (root.child).Add(newNode(100));
    (root.child[0].child).Add(newNode(77));
    (root.child[0].child).Add(newNode(88));
    (root.child[2].child).Add(newNode(1));
    (root.child[3].child).Add(newNode(7));
    (root.child[3].child).Add(newNode(8));
    (root.child[3].child).Add(newNode(9));
    Console.WriteLine("Level order traversal " +
                           "Before Mirroring ");
    LevelOrderTraversal(root);
}
}
// This code is contributed by Rajput-Ji

java 描述语言


输出:

10
2 34 56 100
77 88 1 7 8 9

本文由 Raghav Sharma 供稿。如果你喜欢 GeeksforGeeks 并想投稿,你也可以使用write.geeksforgeeks.org写一篇文章或者把你的文章邮寄到 review-team@geeksforgeeks.org。看到你的文章出现在极客博客主页上,帮助其他极客。
如果你发现任何不正确的地方,或者你想分享更多关于上面讨论的话题的信息,请写评论。


推荐阅读
  • 火星商店问题:线段树分治与持久化Trie树的应用
    本题涉及编号为1至n的火星商店,每个商店有一个永久商品价值v。操作包括每天在指定商店增加一个新商品,以及查询某段时间内某些商店中所有商品(含永久商品)与给定密码值的最大异或结果。通过线段树分治和持久化Trie树来高效解决此问题。 ... [详细]
  • 本文探讨了如何在给定整数N的情况下,找到两个不同的整数a和b,使得它们的和最大,并且满足特定的数学条件。 ... [详细]
  • UNP 第9章:主机名与地址转换
    本章探讨了用于在主机名和数值地址之间进行转换的函数,如gethostbyname和gethostbyaddr。此外,还介绍了getservbyname和getservbyport函数,用于在服务器名和端口号之间进行转换。 ... [详细]
  • 本文探讨了如何在模运算下高效计算组合数C(n, m),并详细介绍了乘法逆元的应用。通过扩展欧几里得算法求解乘法逆元,从而实现除法取余的计算。 ... [详细]
  • 扫描线三巨头 hdu1928hdu 1255  hdu 1542 [POJ 1151]
    学习链接:http:blog.csdn.netlwt36articledetails48908031学习扫描线主要学习的是一种扫描的思想,后期可以求解很 ... [详细]
  • Explore how Matterverse is redefining the metaverse experience, creating immersive and meaningful virtual environments that foster genuine connections and economic opportunities. ... [详细]
  • 题目描述:给定n个半开区间[a, b),要求使用两个互不重叠的记录器,求最多可以记录多少个区间。解决方案采用贪心算法,通过排序和遍历实现最优解。 ... [详细]
  • 前言--页数多了以后需要指定到某一页(只做了功能,样式没有细调)html ... [详细]
  • This document outlines the recommended naming conventions for HTML attributes in Fast Components, focusing on readability and consistency with existing standards. ... [详细]
  • Splay Tree 区间操作优化
    本文详细介绍了使用Splay Tree进行区间操作的实现方法,包括插入、删除、修改、翻转和求和等操作。通过这些操作,可以高效地处理动态序列问题,并且代码实现具有一定的挑战性,有助于编程能力的提升。 ... [详细]
  • 题目Link题目学习link1题目学习link2题目学习link3%%%受益匪浅!-----&# ... [详细]
  • 本文详细介绍了C语言中链表的两种动态创建方法——头插法和尾插法,包括具体的实现代码和运行示例。通过这些内容,读者可以更好地理解和掌握链表的基本操作。 ... [详细]
  • 本文详细探讨了VxWorks操作系统中双向链表和环形缓冲区的实现原理及使用方法,通过具体示例代码加深理解。 ... [详细]
  • 本题涉及一棵由N个节点组成的树(共有N-1条边),初始时所有节点均为白色。题目要求处理两种操作:一是改变某个节点的颜色(从白变黑或从黑变白);二是查询从根节点到指定节点路径上的第一个黑色节点,若无则输出-1。 ... [详细]
  • Linux设备驱动程序:异步时间操作与调度机制
    本文介绍了Linux内核中的几种异步延迟操作方法,包括内核定时器、tasklet机制和工作队列。这些机制允许在未来的某个时间点执行任务,而无需阻塞当前线程,从而提高系统的响应性和效率。 ... [详细]
author-avatar
苏绿儿520
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有