0
点赞
收藏
分享

微信扫一扫

剑指offer07:重建二叉树


剑指offer07:重建二叉树_子树

1.递归的思想:通过前序序列找到根节点,然后在中序中分为左右子树.

2.index:找到值对应的索引位置返回

3.递归函数何时停止的条件很重要

# -*- 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:
return None
root=TreeNode(pre[0])
val=tin.index(pre[0])

root.left=self.reConstructBinaryTree(pre[1:val+1],tin[:val])
root.right=self.reConstructBinaryTree(pre[val+1:],tin[val+1:])
return root



举报

相关推荐

0 条评论