How to construct BST given post-order traversal

前端 未结 5 1675
粉色の甜心
粉色の甜心 2020-12-05 03:44

I know there are ways to construct a tree from pre-order traversal (as an array). The more common question is to construct it, given the inorder and pre-order traversals. In

5条回答
  •  隐瞒了意图╮
    2020-12-05 04:07

    You don't really need the inorder traversal. There's a simple way to reconstruct the tree given only the post-order traversal:

    1. Take the last element in the input array. This is the root.
    2. Loop over the remaining input array looking for the point where the elements change from being smaller than the root to being bigger. Split the input array at that point. This can also be done with a binary search algorithm.
    3. Recursively reconstruct the subtrees from those two sub-arrays.

    This can easily be done either recursively or iteratively with a stack, and you can use two indices to indicate the start and end of the current sub-array rather than actually splitting the array.

提交回复
热议问题