输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if not pre or not tin:  # 结束条件
            return None
        root = TreeNode(pre.pop(0))  #生成根节点
        index = tin.index(root.val)
        root.left = self.reConstructBinaryTree(pre, tin[:index])  #递归生成左子树根节点,tin[:index]都是左子树的结点,生成完才执行下一句生成右子树
        root.right = self.reConstructBinaryTree(pre, tin[index + 1:])  #生成右子树根节点
        return root

递归思想

前序遍历序列中最前面的是根节点,左子树根节点,左子树的一大块,右子树根节点,右子树的一大块

程序每次生成根节点,递归生成左子树根节点,右子树根节点即可

相关文章:

  • 2021-03-31
  • 2021-07-02
  • 2022-01-01
猜你喜欢
  • 2021-05-23
  • 2021-08-08
  • 2021-11-10
  • 2022-01-13
  • 2021-07-14
  • 2021-10-01
  • 2021-11-30
  • 2021-08-06
相关资源
相似解决方案