Skip to content

Conversation

dichlorodiphen
Copy link

Important

Please make sure the file name is lowercase and a duplicate file does not already exist before merging.

Changes

Modified solution to use sublists, which are backed by the original list, avoiding the linear-time copy from copyOfRange. New solution reads closer to the Python solution using slicing.

Copy link
Collaborator

@felivalencia3 felivalencia3 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your solution runs correctly, but it's much slower than the existing code in the repository. There is another way to solve this problem that is closer to Neetcode's original python solution but without the overhead that comes from using the streams and O(n) indexOf lookUps in your code.

@felivalencia3
Copy link
Collaborator

Consider something like this solution.

class Solution {
    private int i = 0;
    private int p = 0;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return build(preorder, inorder, Integer.MIN_VALUE);
    }

    private TreeNode build(int[] preorder, int[] inorder, int stop) {
        if (p >= preorder.length) {
            return null;
        }
        if (inorder[i] == stop) {
            ++i;
            return null;
        }

        TreeNode node = new TreeNode(preorder[p++]);
        node.left = build(preorder, inorder, node.val);
        node.right = build(preorder, inorder, stop);
        return node;
    }
}

@dichlorodiphen dichlorodiphen closed this by deleting the head repository May 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants