为啥没有后序+前序这个组合,非得有个中序?
因为只有中序才能把左子树和右子树分开,才能以此去分割序列
可以想一下,如果我只有后序+前序,我只能确定后序的last为根节点,前序的first为根节点,我找不到左右子树。
中序(l mid r),后序(l r mid),那么后序序列的最后一个=根节点,且中序序列中,在根节点数值左边的为左子树,根节点右边的为右子树。根据这个规律不断分割给出的序列就行
1注意分割的边界处理
2理解递归函数的返回值为新建树的根节点
3python如果切片越界会返回空列表【】
106.中序+后序
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
def recursion(inorder, postorder):
if not inorder:
return
root_val = postorder[-1]
root = TreeNode(root_val)
root_index = 0
for (i, num) in enumerate(inorder):
if num == root_val:
root_index = i
break
left_inorder = inorder[:root_index]
right_inorder = inorder[root_index+1:]
left_postorder = postorder[:root_index]
right_postorder = postorder[root_index:len(postorder)-1]
root.left = recursion(left_inorder, left_postorder)
root.right = recursion(right_inorder, right_postorder)
return root
return recursion(inorder, postorder)
105.前序+中序
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
def recursion_buildTree(preorder, inorder):
if not preorder:
return
root_val = preorder[0]
root = TreeNode(root_val)
if len(preorder) == 1:
return root
count = 0
for i in range(len(inorder)):
if inorder[i] == root_val:
count = i
break
inorder_sub_left = inorder[:count]
inorder_sub_right = inorder[count+1:]
preorder_sub_left = preorder[1:count+1]
preorder_sub_right = preorder[count+1:]
root.left = recursion_buildTree(preorder_sub_left, inorder_sub_left)
root.right = recursion_buildTree(preorder_sub_right, inorder_sub_right)
return root
return recursion_buildTree(preorder, inorder)