My Accepted JAVA solution

  • 0

    Idea is same as the one I posted under postorder and inorder question, which can be found:

    Wish I could get some suggestions as well as advices.

    public class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            if(inorder==null||preorder==null||inorder.length==0||preorder.length==0||preorder.length!=inorder.length) return null;
            int rootVal = preorder[0];
            TreeNode root = new TreeNode(rootVal);
            int rootIndex = arraySearch(inorder, rootVal);
            if(rootIndex>0) root.left = buildTree(Arrays.copyOfRange(preorder,1,rootIndex+1),Arrays.copyOfRange(inorder, 0,rootIndex));
            if(rootIndex<inorder.length-1) root.right = buildTree(Arrays.copyOfRange(preorder,rootIndex+1,preorder.length),Arrays.copyOfRange(inorder, rootIndex+1,inorder.length));
            return root;
        private int arraySearch(int[] A, int target){
            for(int i=0;i<A.length;i++){
                if(A[i]==target) return i;
            return -1;

Log in to reply

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