美文网首页ACM题库~
LeetCode 108. Convert Sorted Arr

LeetCode 108. Convert Sorted Arr

作者: 关玮琳linSir | 来源:发表于2017-09-28 19:45 被阅读8次

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

题意,给我一个升序的数组,让我构建一棵平衡的二叉树。

解析:利用递归的方式,每次选取一个中间位置的数,放在这棵二叉树上。

java代码:

/**
 * 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 == null || nums.length == 0) return null;
        return buildTree(nums, 0, nums.length - 1);
    }
    
    private TreeNode buildTree(int[] nums, int lo, int hi) {
        if (lo > hi) {
            return null;
        }
        int mid = lo + (hi - lo) / 2;
        int data = nums[mid];
        TreeNode treeNode = new TreeNode(data);
        treeNode.left = buildTree(nums, lo, mid - 1);
        treeNode.right = buildTree(nums, mid + 1, hi);
        return treeNode;
    }
}

相关文章

网友评论

    本文标题:LeetCode 108. Convert Sorted Arr

    本文链接:https://www.haomeiwen.com/subject/yvpvextx.html