Concise JAVA solution based on Divide&Conquer


  • 1
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTree(preorder, 0, inorder, 0, inorder.length-1);
    }
    
    public TreeNode buildTree(int[] preorder, int preStart, int[] inorder, int inStart, int inEnd) {
        if (inStart > inEnd || preStart > preorder.length-1)
            return null;
        TreeNode root = new TreeNode(preorder[preStart]);// preorder: root left right
        // Find position of root value in inorder array, so that we can divide inorder array with root, and divide preorder array with inIndex. (left root right)   
        int inIndex = 0;
        for (int i = inStart; i <= inEnd; i++) {
            if (inorder[i] == preorder[preStart]) {
                inIndex = i;
            } 
        }
    
        root.left = buildTree(preorder, preStart + 1, inorder, inStart, inIndex - 1); 
        root.right = buildTree(preorder, preStart + inIndex - inStart + 1, inorder, inIndex + 1, inEnd);
        return root; 
    }

Log in to reply
 

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