Hi,
Could somebody please show me and example of how to iterate through an n-nary tree, where I do not know what n is and n could be different for every node ie the root node could have 3 children and each child might only have 2 children etc, I have used a vector to keep track of every child node of a node, and I'm having trouble working out how to iterate through the tree to find a specific node, could somebody please help.
Thanks.

P.S. each node as a nodeID that ive got to mach to a given nodeID and then add the given node onto that node

Recommended Answers

Answered by Tom Gunn 1,164 in a post from

The algorithm is the same as with a binary tree. The only difference is you loop through the vector to find a matching key and then loop through the links and recursively traverse each one in turn.

Jump to Post

All 2 Replies

The algorithm is the same as with a binary tree. The only difference is you loop through the vector to find a matching key and then loop through the links and recursively traverse each one in turn.

You may want to have a look at tree.hh, which gives you a ready-to-use container class for n-ary trees in C++. Avoids having to worry about details like this :)

http://tree.phi-sci.com

John

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.