从二叉树中的前序遍历序列中查找inorder遍历

时间:2012-10-22 03:00:53

标签: data-structures binary-tree sequence traversal

我只给出了二叉树的预订序遍历序列(例如{a,b,d,c,e}),任务是从中找出有序序列。请原谅我,如果这是一个重复的问题....谢谢

2 个答案:

答案 0 :(得分:1)

我认为你不能根据二叉树的前序遍历找出inorder遍历。正如您所说的二叉搜索树,排序将为您提供顺序遍历。

答案 1 :(得分:0)

我已经在Python中准备了一个函数来从后序遍历中获得前序遍历。也许这会对你有所帮助。

例如,

如果你输入这样的后期订单 输入订单后遍历:ACEDBHIGF

预购将是 预订遍历为GAECFTJOLP

顺序将是 有序遍历为ABCDEFGHI

def from_post_order(post_order_items, order_type="pre"):
    bst = BinarySearchTree()
    values = [item for item in post_order_items]
    root = values[-1]  # the last item in the post_order item is ROOT
    bst.insert(root)  # insert ROOT
    values.pop(-1)  # and remove it from post_order_items

    left_child = []  # the left child of ROOT for Post-order
    right_child = []  # the right child of ROOT for Post-order
    for v in values:
        if v > root:
            right_child.append(v)
        else:
            left_child.append(v)

    for i in range(len(left_child + right_child)):
        if len(left_child) != 0:
            bst.insert(left_child[-1])  # insert left child
            left_child.pop(-1)  # remove the inserted left child from the list

        if len(right_child) != 0:
            bst.insert(right_child[-1])  # insert right child
            right_child.pop(-1)  # remove the inserted right child from the list

    if order_type == "pre":
        print("The pre-order traversal is ")
        bst.preorder(print)
    elif order_type == "in":
        print("The in-order traversal is ")
        bst.inorder(print)
    else:
        print("The post-order traversal is ")
        bst.postorder(print)