my concise accepted solution


  • 0
    Y

    public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
    Map<Integer, Integer> map= new HashMap<>();
    for(int i=0;i<inorder.length;i++){
    map.put(inorder[i],i);
    }
    return buildTree(inorder,inorder.length-1, postorder, postorder.length-1, 0,map);
    }
    public TreeNode buildTree(int[] inorder, int inEnd,int[] postorder, int postStart, int postEnd, Map<Integer, Integer> map){
    if(postStart<postEnd) return null;
    int inRoot=map.get(postorder[postStart]);
    int rightNumber = inEnd-inRoot;
    TreeNode root =new TreeNode(postorder[postStart]);
    root.left=buildTree(inorder,inRoot-1,postorder,postStart-rightNumber-1,postEnd,map);
    root.right=buildTree(inorder,inEnd,postorder,postStart-1,postStart-rightNumber,map);
    return root;
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.