Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/
9 20
/
15 7
第一次的代码:
上题是根据前序中序构造树,这题是根据中序后续构造树,思路都是一样的,首先根据后序找到root,然后再分割左树序列和右树序列进行递归
def c(i,p):
if not i :
return None
root=TreeNode(p[-1])
index=i.index(p[-1])
root.left=c(i[:index],p[:index])
root.right=c(i[index+1:],p[index:-1])
return root
return c(inorder,postorder)
200ms,排名37%
#当然递归方式有很多,也可以根据下标来递归,其实写递归的时候,只需要把起始递归过程写出来就好了
#enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标
def b(il,ir):
if li>ir:
return None
val=postorder.pop()
root=TreeNode(val)
index=tre[val]#得到root下标
root.left=b(il,index)#根据inorder选择左右树
root.right=b(index+1,ir)
return root
tre={val:ind for ind , val in enumerate(inorder) }
188ms,排名42%