剑指offer刷题记录之重建二叉树

1. 题目描述

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

2. 递归解题

2.1 分析

前序遍历:根→左→右
中序遍历:左→根→右

  • 由前序遍历序列pre={1,2,4,7,3,5,6,8}可知根结点是1;
  • 则在中序遍历序列in={4,7,2,1,5,3,8,6}中找到1,便可知1所在位置的左侧是左子树,1所在位置的右侧是右子树,也可以得到左子树和右子树的长度分别为3和4;
  • 递归调用:将中序遍历中根节点的左子树和右子树分别看成一颗树,再到前序遍历中找到左子树和右子树各自的节点,在找到左子树的根节点。
  • 以左子树为例,{4,7,2}长度为3,则其在前序遍历中对应根节点后的3个元素,这三个元素中2再是左子树的根节点,依次递归。

2.2 代码

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 len(pre) == 0:
            return None
        elif len(pre) == 1:
            return TreeNode(pre[0])
        else:
            tree = TreeNode(pre[0])
            rootindex = tin.index(pre[0])
            tree.left = self.reConstructBinaryTree(pre[1:rootindex+1], tin[:rootindex])
            tree.right = self.reConstructBinaryTree(pre[rootindex+1:], tin[rootindex+1:])
            return tree

3. 二叉树基础知识

c++版本
python版本

发布了38 篇原创文章 · 获赞 98 · 访问量 36万+

猜你喜欢

转载自blog.csdn.net/xijuezhu8128/article/details/104679392
今日推荐