Clean Java 6ms recursive


  • 0
    V
        HashMap<Integer, Integer> inordHm;
        int pind = 0;
        public TreeNode buildTree(int[] preorder, int[] inorder) 
        {
            inordHm = new HashMap<Integer, Integer>();
            for(int i = 0; i < inorder.length; i++)
                inordHm.put(inorder[i], i);
            return recBuild(preorder, 0, inorder.length - 1);
        }
        TreeNode recBuild(int[] preorder, int s, int e)
        {
            if(s > e)
                return null;
            int iind = inordHm.get(preorder[pind]);
            TreeNode toRet = new TreeNode(preorder[pind]);
            pind++;
            toRet.left = recBuild(preorder, s, iind - 1);
            toRet.right = recBuild(preorder, iind + 1, e);
            return toRet;
        }

Log in to reply
 

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