In-order tree traversal for non-binary trees

孤者浪人 提交于 2019-12-06 05:16:43

问题


Does the term "inorder traversal" have a well-defined meaning for trees wider than binary trees, or are "pre-" and "post-" order the only type of DFS that makes sense? I mean with n>2 children per-node.
I guess for n that is even it might mean going to the 'root' after n/2 children, but is this ever used like this? And what about odd n?


回答1:


The inorder traversal will continue to be well defined only if you explicitly partition the children set into left children and right children.

To see this, note that the inorder traversal actually enumerates nodes in the order in which they will appear if we flatten the tree (or equivalently, the order in which the nodes will appear if we gaze over the tree starting from left).

Thus, for an n-ary tree, you will process the left children set first, followed by the parent and the right children set.

For example, consider the following tree :

If we define the set of left children to be the first 2 child nodes from the left, and the set of right children as the single last node, we will get the following inorder traversal :

14, 15, 5, 16, 17, 18, 6, 19, 2, 20, 21, 7, 8, 9, 3, 10, 1, 11, 12, 4, 13

The method of choosing the left and right children set will depend on the problem in hand.



来源:https://stackoverflow.com/questions/23778489/in-order-tree-traversal-for-non-binary-trees

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!