LeetCode106-从中序与后序遍历序列构造二叉树
最近要参加互联网+的比赛了
还要写专利
好日子过完了
开始新一轮的紧张备战了
加油吧!!!
106-从中序与后序遍历序列构造二叉树
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
思路:
这一题和第105题-从前序与中序遍历序列构造二叉树其实大同小异,大家可以先看看我之前写的这篇博文。
https://blog.****.net/weixin_36431280/article/details/89813740
这里面我已经讲的算是比较清楚了,直接上代码吧!
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if len(postorder) == 0:
return
# 获得根节点在中序序列中的下标值
mid_index = inorder.index(postorder[-1])
# 开始创建节点
root = TreeNode(postorder[-1])
# inorder[:mid_index], postorder[:mid_index] 表示着中序序列和后序序列中对应的左子树的值
root.left = self.buildTree(inorder[:mid_index], postorder[:mid_index])
# inorder[mid_index+1:], postorder[mid_index:len(postorder)-1] 表示着中序序列和后序序列中对应的右子树的值
root.right = self.buildTree(inorder[mid_index+1:], postorder[mid_index:len(postorder)-1])
return root
def traverse(self, root):
if root is None:
return
print(root.val)
self.traverse(root.left)
self.traverse(root.right)
if __name__ == "__main__":
preorder = [9,3,15,20,7]
inorder = [9,15,7,20,3]
BTree = Solution().buildTree(preorder, inorder)
Solution().traverse(BTree)
执行效率较差,在25%左右。