Clean recursive Java Solution


  • 0
    C
      public TreeNode buildTree(int[] inorder, int[] postorder) {
        return buildTreeIntern(inorder, postorder, inorder.length - 1, postorder.length - 1, inorder.length);
      }
    
      private TreeNode buildTreeIntern(int[] inorder, int[] postorder, int inIndex, int postIndex, int size) {
        if(size <= 0) {
          return null;
        }
        TreeNode rv = new TreeNode(postorder[postIndex]);
    
        for(int i = 0; i < size; i++) {
          if(postorder[postIndex] == inorder[inIndex - i]) {
            rv.right = buildTreeIntern(inorder, postorder, inIndex, postIndex - 1, i);
            rv.left = buildTreeIntern(inorder, postorder, inIndex - i - 1, postIndex - i - 1, size - i - 1);
            break;
          }
        }
    
        return rv;
      }

Log in to reply
 

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