【问题标题】:Find the inorder traversal from its preorder traversal sequence in binary tree从二叉树的前序遍历序列中找到中序遍历
【发布时间】:2012-10-22 03:00:53
【问题描述】:

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

【问题讨论】:

  • 只是在这里做一个说明,如果树是具有数字键值的二叉搜索树,那么我知道中序遍历序列是给定前序或后序的排序序列顺序遍历序列。但我想知道如果这棵树不是 BST 而是只有字母标签的 BT 怎么办。

标签: data-structures binary-tree sequence traversal


【解决方案1】:

我认为您无法仅根据二叉树的前序遍历来找出中序遍历。正如你所说的二叉搜索树,排序会给你中序遍历。

【讨论】:

    【解决方案2】:

    我在 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)
    

    【讨论】:

      猜你喜欢
      • 2021-03-08
      • 2023-01-09
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      相关资源
      最近更新 更多