7. 重建二叉树
重建二叉树
http://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6
- 假如有前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
- 从前序pre知根节点是第一个元素1,从中序知元素1前面的[4,7,2]都是左子树,[5,3,8,6]是右子树
- 递归可建得二叉树
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if not pre or not tin:
return None
root = TreeNode(pre[0])
k = tin.index(pre[0])
root.left = self.reConstructBinaryTree(pre[1:k+1],tin[0:k])
root.right = self.reConstructBinaryTree(pre[k+1:],tin[k+1:])
return root