通过先序和中序遍历重建二叉树

题目描述

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

分析:

前序遍历就是先根序,然后左子树,右子树。
中序遍历就是先左子树,然后右子树。

前序遍历中第一个1就是root节点,中序遍历中1的左边就是它的左子树,右边就是右子树
然后看中序遍历里的1左边{4,7,2},和前序遍历里的{2,4,7}又是一组前序和中序遍历,{3,5,6,8}和{5,3,8,6}也是一组,我们就可以通过递归解决了。

代码实现:

# -*- coding:utf-8 -*-
# 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:  # 如果没有值就None
            return None
        if len(pre) != len(tin): # 如果个数不一样,就None
            return None
        root = pre[0]   # 取出节点
        root_node = TreeNode(root) # 实例化生成根节点
        
        # 通过列表点index获取根节点在中序遍历中的位置。
        root_index = tin.index(root) 
        
        tinleft = tin[:root_index]   # 取出1 左边的节点作为新的中序遍历
        tinright = tin[root_index+1:]  # 取出右边
        
        preleft = pre[1:root_index+1] #注意左闭右开 对应取出
        preright = pre[root_index+1:]
        
        root_left = self.reConstructBinaryTree(preleft, tinleft)
        root_right = self.reConstructBinaryTree(preright, tinright)
        root_node.left = root_left
        root_node.right = root_right
        return root_node

递归完,注意实例化节点,给他加上左子树和右子树。

发布了89 篇原创文章 · 获赞 7 · 访问量 2196

猜你喜欢

转载自blog.csdn.net/qq_36710311/article/details/105445483