Leetcode 108. Convert Sorted Array to Binary Search Tree
Posted DCREN
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}
}
以上是关于Leetcode 108. Convert Sorted Array to Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 108. Convert Sorted Array to Binary Search Tree
Leetcode 108. Convert Sorted Array to Binary Search Tree
LeetCode_108. Convert Sorted Array to Binary Search Tree
[LeetCode]题解(python):108-Convert Sorted Array to Binary Search Tree