Leetcode 108. Convert Sorted Array to Binary Search Tree

题目链接

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/

题目描述

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.

代码

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

posted @ 2018-08-28 12:23  DCREN  阅读(180)  评论(0编辑  收藏  举报