reconstructing a tree from its preorder and postorder lists

前端 未结 7 1888
既然无缘
既然无缘 2020-11-28 04:26

Consider the situation where you have two lists of nodes of which all you know is that one is a representation of a preorder traversal of some tree and the other a represent

7条回答
  •  星月不相逢
    2020-11-28 04:53

    The preorder and postorder traversals are sufficient to reconstruct the tree, assuming the nodes are uniquely named. The key to creating the algorithms to do so is to understand that

    X is an ancestor of Y iff X precedes Y in the preorder and is after Y in the postorder.

    Given this, we can always find all the descendants of any node. The descendants of X always immediately follow X in the preorder, and precede X in the postorder. So once we know we're interested in producing the subtree rooted at X, we can extract the preorder and postorder traversal for the subtree rooted at X. This leads naturally to a recursive algorithm, once we realize that the node immediately after X must be its leftmost child, if it is a descendant at all.

    There is also a stack-based implementation, which iterates through the preorder nodes, and keeps on the stack any nodes which are candidates to be the direct parent of the next preorder node. For each preorder node, repeatedly pop all nodes off the stack which are not parents of the next preorder node. Make that node a child of the top node on the stack, and push the child onto the stack.

提交回复
热议问题