Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
原题链接:https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
题目:给定一个升序排列元素的数组,将其转换成高度平衡的二叉树。
思路:已经排序。则从中间劈开,中间元素为树的根,左右递归构建。
public TreeNode sortedArrayToBST(int[] num) {
return sortedArrayToBST(num,0,num.length - 1);
}
public TreeNode sortedArrayToBST(int[] num,int start,int end) {
if(start > end)
return null;
int mid = (start + end)/2;
TreeNode node = new TreeNode(num[mid]);
node.left = sortedArrayToBST(num,start,mid-1);
node.right = sortedArrayToBST(num,mid+1,end);
return node;
}
// Definition for binary tree
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}