简体   繁体   English

如何在C ++中获取非二叉树中特定节点的所有子节点

[英]How to get all child nodes of a specific node in non-binary tree in C++

I'm being stuck because I don't know how to get all child nodes of a specific node in non-binary tree. 我被困住了,因为我不知道如何在非二叉树中获取特定节点的所有子节点。

For example, the root node is A. 例如,根节点是A。

A = {B, C} A = {B,C}

B = {D, E, F} B = {D,E,F}

E = {G} E = {G}

I want to get all child nodes of B = {D, E, F, G} 我想获取B = {D,E,F,G}的所有子节点

How can I do? 我能怎么做? Thank you very much. 非常感谢你。

You can obtain child nodes recursively. 您可以递归获取子节点。

First, walk the tree to obtain the initial node B . 首先,遍历树以获得初始节点B After that, apply this recursive pseudocode: 之后,请应用以下递归伪代码:

void get_children(Node *node, list<Node*>& res) {
    for each child in node->children {
        res.add(child);
        get_children(child, res);
    }
}

Pass B to get_children , along with an empty list of nodes. B连同空节点列表传递给get_children The function will add all children to the list passed into it. 该函数会将所有子项添加到传递给它的列表中。 Make sure that you pass your list by reference; 确保您通过引用传递了列表; otherwise, the function will not modify your list. 否则,该功能将不会修改您的列表。

Assuming that your tree is directed, a simple graph traversal algorithm (BFS or DFS) will do the job for you. 假设您的树是有方向的,那么简单的图形遍历算法(BFS或DFS)将为您完成工作。

Breadth-First-Search(Graph, startNode):

    create empty queue Q      
    Q.enqueue(startNode)                      
    while Q is not empty:           
        current = Q.dequeue()
        for each node n that is adjacent to current:
            print n
            Q.enqueue(n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM