[LeetCode] 106. Construct Binary Tree from Postorder and Inorder Traversal_Medium tag: Tree Traversal

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

这个题目思路跟[LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal_Medium tag: Tree Traversal一样, 只是root是postorder[-1], 而inorder[0] 而已, 本质一样.

Code:

class Solution:
def buildTree(self, postorder, inorder):
if not postorder or not inorder: return
root, index = TreeNode(postorder[-1]), inorder.index(postorder[-1])
root.left = self.buildTree(postorder[:index], inorder[:index])
root.right = self.buildTree(postorder[index: -1], inorder[index+1:])
return root
上一篇:oracle 11g 一直提示 严重: 监听程序未启动或数据库服务未注册到该监听程序


下一篇:Html5 监听拦截Android返回键方法详解