重建二叉树
题目描述
Python 最终提交
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if pre and tin:
# 找到根节点
root = TreeNode(pre[0])
# 计算根节点在中序中的索引
root_position_in_order = tin.index(root.val)
# 计算左子树长度
left_length = root_position_in_order
right_length = len(tin) - root_position_in_order - 1
# 比该索引值小的为左子树
if left_length > 0:
root.left = Solution().reConstructBinaryTree(pre[1:root_position_in_order + 1],
tin[:root_position_in_order])
# 计算右子树长度
if right_length > 0:
# 比该索引值大的为右子树
root.right = Solution().reConstructBinaryTree(pre[root_position_in_order + 1:],
tin[root_position_in_order + 1:])
return rootC/C++ 最终提交
Last updated