简体   繁体   中英

How to find preorder traversal from given postorder traversal of binary search tree

I have a post-order traversal of a BST like [3,6,5,1,12,16,15,10,20,7] and I want to find its pre-order traversal like [7,1,5,3,6,20,10,15,12,16]. Is it possible to find a recursive solution without constructing the tree? [Edited]

Here is a recursive function without building the tree. It traverses the post order list from the end to the beginning, since that represents almost the required order, with the exception that children are visited in opposite order:

def preordered(postorder):
    def recur(granny, parent):
        if not postorder or postorder[-1] < min(granny, parent):
            return []
        value = postorder.pop()
        right = recur(parent, value)
        left = recur(parent, value)
        return [value] + left + right

    low = min(postorder)
    postorder = postorder[:]
    return recur(low, low)

result = preordered([3,6,5,1,12,16,15,10,20,7])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM