其他分享
首页 > 其他分享> > 重构二叉树

重构二叉树

作者:互联网

剑指offer 牛客网:重构二叉树

# -*- coding: utf-8 -*-
"""
Created on Mon Apr  8 14:18:46 2019

@author: Administrator
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如输入前序遍历序列{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 her
        if len(pre) == 0:   #如果没有节点就直接返回None
            return None
        elif len(pre) == 1: #如果只有一个节点就直接是头结点了,直接返回
            return TreeNode(pre[0])
        else: 
            tin_left = tin[:tin.index(pre[0])]  #截取中左区域
            tin_right = tin[tin.index(pre[0])+1:]   #截取中右区域
            pre_left = pre[1:len(tin_left)+1]   #截取前左区域
            pre_right = pre[len(tin_left)+1:]   #截取前右区域
            res = TreeNode(pre[0])  #头结点为前的第0个节点
            res.left = Solution.reConstructBinaryTree(self,pre_left,tin_left)   #递归,左节点是前左和中左
            res.right = Solution.reConstructBinaryTree(self,pre_right,tin_right)#递归,右节点是前右和中右
            return res
    #前序遍历
    def preorder(self,node):
        if node:
            print(node.val)
            Solution.preorder(self,node.left)
            Solution.preorder(self,node.right)
    # 中序遍历
    def inorder(self,node):
        if node:
            Solution.inorder(self,node.left)
            print(node.val)
            Solution.inorder(self,node.right)
    #后序遍历
    def postorder(self,node):
        if node:
            Solution.postorder(self,node.left)
            Solution.postorder(self,node.right)
            print(node.val)
if __name__ == '__main__':
    pre = [1,2,4,7,3,5,6,8]
    tin = [4,7,2,1,5,3,8,6]
    solution = Solution()
    tree = solution.reConstructBinaryTree(pre,tin)
    solution.preorder(tree)

 

标签:pre,重构,node,self,Solution,tin,二叉树,left
来源: https://www.cnblogs.com/missidiot/p/10670821.html