python3
采用递归思想,思路:由前序遍历可知第一个节点即为根结点,然后将此节点对应在中序节点的位置将中序遍历分为左右子树,重新得到子树的前序,中序遍历,依次递归给下一层.
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if len(tin) == 0:
return None
root = TreeNode(pre[0]) #前序遍历第一个值为根节点
index = tin.index(root.val) #因为没有重复元素,所以可以直接根据值来查找根节点在中序遍历中的位
root.left = self.reConstructBinaryTree(pre[1:index+1],tin[:index])
root.right = self.reConstructBinaryTree(pre[index+1:],tin[index+1:])
return root
京公网安备 11010502036488号