4.重建二叉树(python)
根据前序和中序重建二叉树:
1 class Solution: 2 # 返回构造的TreeNode根节点 3 def reConstructBinaryTree(self, pre, tin): 4 # write code here 5 if len(pre)==0: 6 return None 7 if len(pre) == 1: 8 return TreeNode(pre[0]) 9 root = TreeNode(pre[0]) 10 tinL = tin[0:tin.index(pre[0])] 11 12 tinR = tin[tin.index(pre[0])+1:] 13 root.left = self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],tinL) 14 root.right = self.reConstructBinaryTree(pre[tin.index(pre[0])+1:],tinR) 15 return root
2019-12-31 12:43:06