Simple AC recursive java solution, inspired by using preorder and inorder to construct the tree


  • 0
    F
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return helper(postorder,postorder.length - 1, inorder, 0, inorder.length - 1);
    }
    public TreeNode helper(int[] postorder, int postIndex, int[] inorder, int in_start, int in_end){
        if(postIndex < 0 || in_start > in_end) {return null;}
        TreeNode root = new TreeNode(postorder[postIndex]);
        int cur_root = 0;
        for(int i = 0; i < inorder.length; i++){
            if(inorder[i] == root.val){
                cur_root = i;
            }
        }
        root.right = helper(postorder,postIndex-1,inorder,cur_root + 1, in_end);
        root.left = helper(postorder,postIndex - (in_end - cur_root + 1), inorder, in_start, cur_root - 1);
        return root;
    }
    

    }


Log in to reply
 

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