What did I miss in the solution ? Failing for input [1,2], [2,1]. Gives output as {2}.


  • 0
    V
    public class Solution {
        public static int preIndex = 0;
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            return build(preorder, inorder, 0, inorder.length-1);
        }
        
        public TreeNode build(int[] p, int[] in, int left, int right){
            if(left > right)
                return null;
            if(preIndex >= p.length)
                return null;
            TreeNode head = new TreeNode(p[preIndex]);
            preIndex++;
            
            int i=0;
            for(i=left; i<=right; i++){
                if(in[i] == head.val)
                    break;
            }
            
            head.left = build(p, in, left, i-1);
            head.right = build(p, in, i+1, right);
            return head;
        }
        
    }

Log in to reply
 

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