Concise solution in Java


  • 0
    W
     public class Solution {
     public TreeNode buildTree(int[] inorder, int[] postorder) {
        return help(inorder, postorder, postorder.length - 1 , 0, inorder.length - 1);
    }
    public TreeNode help(int[] inorder, int[] postorder, int end, int Instart, int Inend){
        if(Instart > Inend){
            return null;
        }
        TreeNode root = new TreeNode(postorder[end]);
        int index = 0;
        for(int i = Instart; i <= Inend; i++){
            if(inorder[i] == root.val){
                index = i;
                break;
            }
        }
        root.right = help(inorder, postorder, end - 1, index + 1, Inend);
        root.left = help(inorder, postorder, end - 1 -(Inend - index), Instart, index - 1);
        return root;
    }
    

    }


Log in to reply
 

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