recursive java solution


  • 0
    F
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            return buildTree(preorder, 0, preorder.length, inorder, 0, inorder.length);
        }
    
        private TreeNode buildTree(int[] preorder, int from1, int to1, int[] inorder, int from2, int to2) {
            if (from1 == to1) {
                return null;
            }
            int val = preorder[from1];
            TreeNode root = new TreeNode(val);
            int leftSize = 0;
            for (int i = from2; i < to2; i++) {
                if (inorder[i] == val) {
                    break;
                }
                leftSize++;
            }
            root.left = buildTree(preorder, from1 + 1, from1 + 1 + leftSize, inorder, from2, from2 + leftSize);
            root.right = buildTree(preorder, from1 + 1 + leftSize, to1, inorder, from2 + 1 + leftSize, to2);
            return root;
        }

Log in to reply
 

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