Java:
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return build(inorder, 0, inorder.length-1, postorder, 0,postorder.length-1);
}
public TreeNode build(int[] inorder, int in_str, int in_end, int[] postorder, int pos_str, int pos_end){
if(in_str > in_end || pos_str > pos_end) return null;
TreeNode root = new TreeNode(postorder[pos_end]);
int index = 0;
for(int i=0;i<=in_end;i++){
if (inorder[i] == root.val){
index = i;
break;
}
}
root.left = build(inorder, in_str, index-1, postorder, pos_str, pos_str+index-in_str-1);
root.right = build(inorder, index+1, in_end, postorder, pos_str+index-in_str, pos_end-1);
return root;
}
}
Python:
class Solution:
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if inorder:
ind = inorder.index(postorder.pop())
root = TreeNode(inorder[ind])
root.right = self.buildTree(inorder[ind+1:], postorder)
root.left = self.buildTree(inorder[:ind], postorder)
return root