# -*- 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.pop(0))
index = tin.index(root.val)
root.left = self.reConstructBinaryTree(pre, tin[:index])
root.right = self.reConstructBinaryTree(pre, tin[index + 1:])
return root关于“root.left = self.reConstructBinaryTree(pre, tin[:index])”中的pre为什么不需要指定范围?
重建时先建立左子树时,会将pre中的内容一个个pop掉,这样到建立右子树时,pre中已经不包含左子树中的内容了。


京公网安备 11010502036488号