知识点:二叉树,递归
思路:
pre为先序遍历序列,tin为中序遍历序列
- pre的第一个元素为根节点的值,tin以root为分界点
- root的索引为i
- tin前半部分[:i]为左子树,后半部分[i+1:]为右子树
- pre[1:i+1]为左子树,[i+1:]为右子树
- 递归构造
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 not pre and not tin:
return None
if set(pre) != set(tin):
return None
root = TreeNode(pre[0])
i = tin.index(pre[0])
root.left = self.reConstructBinaryTree(pre[1:i+1], tin[:i]) # 左子树
root.right = self.reConstructBinaryTree(pre[i+1:], tin[i+1:]) # 右子树
return root