python
这里使用了 list.index()
, 这个非常有用
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
# guard
if len(inorder) ==0:
return None
root = TreeNode(postorder.pop(-1))
if len(postorder)>0:
left_in = inorder[:inorder.index(root.val)]
right_in = inorder[inorder.index(root.val)+1:]
if(len(left_in)>0):
left_post = postorder[:len(left_in)]
root.left = self.buildTree(left_in,left_post)
if(len(right_in)>0):
right_post = postorder[len(left_in):]
root.right = self.buildTree(right_in, right_post)
return root
网友评论