My Java recursive solution O(n)

  • 0
    public TreeNode buildTree(int[] inorder, int[] postorder) {
            if(inorder.length == 0 || inorder.length != postorder.length) return null;
            return buildTree(inorder,postorder,0,inorder.length-1,0,postorder.length-1);
        public TreeNode buildTree(int[] inorder, int[]postorder, int ilow, int ihigh, int plow, int phigh) {
             TreeNode root = new TreeNode(postorder[phigh]);
             int i=-1;
             for(i = ilow; i <= ihigh; i++) {
                   if(root.val == inorder[i]) {
              if(i != ilow) root.left = buildTree(inorder, postorder, ilow, i-1, plow,plow+i-ilow-1);
              if(i != ihigh) root.right = buildTree(inorder,postorder, i+1, ihigh, plow+i-ilow, phigh-1);
              return root;

  • 0

    Brilliant solution, but I still cannot figure minus ilow in plow+i-ilow-1 in the recursion. Could you explain it?

Log in to reply

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