20ms Java Solution


  • 0
    P
    public class Solution {
        public TreeNode buildTree(int[] inorder, int[] postorder) {
             if(postorder==null||inorder==null)return null;
           return  buildtree(postorder,inorder,0,postorder.length-1,0,inorder.length);
        }
         public TreeNode buildtree(int[] postorder, int[] inorder,int prestart,int preend,int instart,int inend){
            if(prestart==preend&&instart==inend&&postorder[prestart]==inorder[instart])return new TreeNode(postorder[prestart]);
            if(prestart>preend||instart>inend)return null;
            if(prestart==preend&&instart==inend&&postorder[prestart]!=inorder[instart])return null;
            TreeNode node = new TreeNode(postorder[preend]);
            int i = instart;
            for(;i<=inend;i++){
                if(postorder[preend]==inorder[i])
                break;
            }
            
            if(i>inend)return null;
            i = i - instart;
            TreeNode left = buildtree(postorder,inorder,prestart,prestart+i-1,instart,i+instart-1);
            TreeNode right = buildtree(postorder,inorder,prestart+i,preend-1,i+1+instart,inend);
            node.left  = left;
            node.right = right;
            return node;
        }
    }

Log in to reply
 

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