LeetCode OJ 108. Convert Sorted Array to Binary Search Tree

时间:2024-04-11 13:36:29

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

把一个有序的数组转换为一颗平衡二叉搜索树。每次找到中间节点作为根节点,根节点左边部分转换为左子树,右边部分转换为右子树。代码如下:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length == 0) return null;
return changeToBST(nums, 0, nums.length-1);
} public TreeNode changeToBST(int[] nums, int left, int right){
int mid = (right - left)/2 + left;
TreeNode root = new TreeNode(nums[mid]);
if(left==mid) root.left = null;
else root.left = changeToBST(nums, left, mid-1);
if(right==mid) root.right = null;
else root.right = changeToBST(nums, mid+1, right);
return root;
}
}