lolyoshi - 10 months ago 74

C++ Question

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 = {B, C}

B = {D, E, F}

E = {G}

I want to get all child nodes of B = {D, E, F, G}

How can I do? Thank you very much.

Answer

You can obtain child nodes recursively.

First, walk the tree to obtain the initial node `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. 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.

Source (Stackoverflow)