# -*- 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 len(pre)==0:
return None
else:
pos = tin.index(pre[0])
tree = TreeNode(pre[0])
tree.left=self.reConstructBinaryTree(pre[1:pos+1],tin[:pos])
tree.right=self.reConstructBinaryTree(pre[pos+1:],tin[pos+1:])
return tree
第一种解法:
第一,检查长度是否为零
第二,计算root的位置
第三,创建树的实例,添加左右叶子。
第二种差不多,但是比较简洁
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def reConstructBinaryTree(self, pre, tin):
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
学到的知识:
函数还有写完就可以再次调用自己,用self.fun()
在另外一个list里面找数值一样的索引 y.index(x[])
检查是否为空集可以这样
if not x or not y:
return None