Pre-order to post-order traversal

后端 未结 11 1501
挽巷
挽巷 2020-12-23 21:56

If the pre-order traversal of a binary search tree is 6, 2, 1, 4, 3, 7, 10, 9, 11, how to get the post-order traversal?

11条回答
  •  暖寄归人
    2020-12-23 22:38

    I know this is old but there is a better solution.

    We don't have to reconstruct a BST to get the post-order from the pre-order.

    Here is a simple python code that does it recursively:

    import itertools
    
    def postorder(preorder):
        if not preorder:
            return []
        else:
            root = preorder[0]
            left = list(itertools.takewhile(lambda x: x < root, preorder[1:]))
            right = preorder[len(left) + 1:]
            return postorder(left) + postorder(right) + [root]
    
    if __name__ == '__main__':
        preorder = [20, 10, 6, 15, 30, 35]
        print(postorder(preorder))
    

    Output:

     [6, 15, 10, 35, 30, 20]
    

    Explanation:

    We know that we are in pre-order. This means that the root is at the index 0 of the list of the values in the BST. And we know that the elements following the root are:

    • first: the elements less than the root, which belong to the left subtree of the root
    • second: the elements greater than the root, which belong to the right subtree of the root

    We then just call recursively the function on both subtrees (which still are in pre-order) and then chain left + right + root (which is the post-order).

提交回复
热议问题