Java O(n) solution, 1 ms, beats 99%, two pointers

  • 1
    class Solution {
        private int inIndex=0, preIndex=0;
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            return helper(preorder, inorder, Integer.MAX_VALUE);
        private TreeNode helper(int[] preorder, int[] inorder, int target) {
            if (inIndex >= inorder.length || inorder[inIndex] == target) {
                return null;
            TreeNode root = new TreeNode(preorder[preIndex]);
            root.left = helper(preorder, inorder, root.val);
            root.right = helper(preorder, inorder, target);
            return root;

Log in to reply

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