Java 5ms AC solution, beats 83%


  • 0
    B
    public class Solution {
        Map<Integer, Integer> map;
        int[] preorder;
        int[] inorder;
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            map = new HashMap<Integer, Integer>(inorder.length + 1, 1);
            this.preorder = preorder;
            this.inorder = inorder;
            for (int i = 0; i < inorder.length; i++) {
                map.put(inorder[i], i);
            }
            return builder(0, 0, inorder.length - 1);
        }
        
        public TreeNode builder(int p, int i1, int i2) {
            if (i1 > i2) return null;
            int mid = map.get(preorder[p]);
            int pRight = p + mid - i1 + 1;
            TreeNode cur = new TreeNode(preorder[p]);
            cur.left = builder(p + 1, i1, mid - 1);
            cur.right = builder(pRight, mid + 1, i2);
            return cur;
        }
    }
    

Log in to reply
 

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