问题
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