根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7] 后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3 / \ 9 20 / \ 15 7
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
n = len(inorder)
m = len(postorder)
if m != n:
return None
mapper = {}
for index,num in enumerate(inorder):
mapper[num] = index
return self.build(postorder,0,n-1,mapper,0,m-1)
def build(self,postorder,postLeft,postRight,mapper,inLeft,inRight):
if postLeft>postRight or inLeft>inRight:
return None
root_val = postorder[postRight]
root = TreeNode(root_val,None,None)
index = mapper.get(root_val)
root.left = self.build(postorder,postLeft,postRight-inRight+index-1,mapper,inLeft,index-1)
root.right = self.build(postorder,postRight-inRight+index,postRight-1,mapper,index+1,inRight)
return root