[LeetCode]第十九题 :有序数组转换成平衡二叉树

题目描述:

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

题目解释:

给出一个排序好的数组,将它转换成平衡二叉树。

平衡二叉树的左右子树高度不能超过1.

题目解法:

1.我的解法:其实想法很简单,平衡二叉树,其左子树的值都小于根节点,右子树的值都大于根节点。那么从数组的中间取值作为根节点,左子树是从数组的0到中间位置 - 1,右子树是从中间位置 + 1到末尾,然后递归生成左右子树即可。代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums.length == 0) return null;
        int index = nums.length / 2;
        TreeNode node = new TreeNode(nums[index]);
        int[] leftArray = new int[index];
        for(int i = 0;i

你可能感兴趣的:(LeetCode)