recursive solution.
the last element in the postorder array is always the root
pass index instead of array to save memory
# 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
"""
def buildTree(i_start,i_end,p_start,p_end):
if i_start==i_end:return None
#print 'create root',postorder[p_end-1]
root=TreeNode(postorder[p_end-1])
root_idx=inorder[i_start:i_end].index(root.val)
#print 'create left root'
root.left=buildTree(i_start,i_start+root_idx,p_start,p_start+root_idx)
#print 'create right root'
root.right=buildTree(i_start+root_idx+1,i_end,p_start+root_idx,p_end-1)
return root
if not inorder or not postorder:
return None
return buildTree(0,len(inorder),0,len(postorder))
网友评论