文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. 问题描述
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
2. 求解
这个题主要是根据一个有序数组构造二叉查找树(树的左结点小于根节点,根节点小于右结点,子树具有同样的性质)。构造方法主要是递归,每次构建子树时都需要将数组分成左右两半,左边的构建左子树,右边的构建右子树,中间元素构造根节点。
/**
* 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) {
return buildBinarySearchTree(nums, 0, nums.length - 1);
}
public TreeNode buildBinarySearchTree(int[] nums, int start, int end) {
if(start > end) {
return null;
}
int mid = (start + end) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = buildBinarySearchTree(nums, start, mid - 1);
root.right = buildBinarySearchTree(nums, mid + 1, end);
return root;
}
}