Loading

LeetCode problem#108

Convert Sorted Array to Binary Search Tree

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

35 lines
1/**
2 * Definition for a binary tree node.
3 * public class TreeNode {
4 *     int val;
5 *     TreeNode left;
6 *     TreeNode right;
7 *     TreeNode() {}
8 *     TreeNode(int val) { this.val = val; }
9 *     TreeNode(int val, TreeNode left, TreeNode right) {
10 *         this.val = val;
11 *         this.left = left;
12 *         this.right = right;
13 *     }
14 * }
15 */
16class Solution {
17    private TreeNode buildBSTFromSortedArray(int[] nums, int lower, int upper) {
18        if (lower > upper) {
19            return null;
20        }
21
22        // Remove Math.ceil to get the other variation
23        int mid = (int) Math.ceil((lower + upper) / 2.0);
24        TreeNode newTreeNode = new TreeNode(nums[mid]);
25
26        newTreeNode.left = buildBSTFromSortedArray(nums, lower, mid - 1);
27        newTreeNode.right = buildBSTFromSortedArray(nums, mid + 1, upper);
28
29        return newTreeNode;
30    }
31
32    public TreeNode sortedArrayToBST(int[] nums) {
33        return buildBSTFromSortedArray(nums, 0, nums.length - 1);
34    }
35}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.