【LeetCode】 108. Convert Sorted Array to Binary Search Tree 将有序数组转换为二叉搜索树(Easy)(JAVA)

【LeetCode】 108. Convert Sorted Array to Binary Search Tree 将有序数组转换为二叉搜索树(Easy)(JAVA)

题目地址: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

题目描述:

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、二叉搜索树的前序遍历是一个升序有序数组
2、取中间值,左边的为左子树,右边的为右子树,不断迭代

/**
 * 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 sH(nums, 0, nums.length - 1);
    }

    public TreeNode sH(int[] nums, int start, int end) {
        if (start > end) return null;
        int mid = (start + end) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = sH(nums, start, mid - 1);
        root.right = sH(nums, mid + 1, end);
        return root;
    }
}

执行用时 : 0 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 39.1 MB, 在所有 Java 提交中击败了 8.70% 的用户

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/105824195
今日推荐