最近在刷leetcode算法的入门题,刷到二叉树,一开始浑浑噩噩,后来掌握了套路,自己搞定一个,而且很优雅,比留言中的大部分都优雅,嗯,写个日志自嗨一把。
所有刷题都提交到我的github上了,具体位置:windanchaos的github

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
题目要求:
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1

示例:

给定有序数组: [-10,-3,0,5,9],

一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:

0
/ \
-3 9
/ /
-10 5

来源:力扣(LeetCode
链接:https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

我的解法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
<!-- more -->
/*
执行用时 :1 ms, 在所有 Java 提交中击败了99.76%的用户
内存消耗 :37.2 MB, 在所有 Java 提交中击败了97.44%的用户
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length==0 || null == nums) return null;
//只有一个元素的情况
if(nums.length==1) return new TreeNode(nums[0]);
//数量大于1,构建节点
TreeNode root=new TreeNode(nums[nums.length/2]);
//构建左右子树
root.left=sortedArrayToBST(Arrays.copyOfRange(nums,0,nums.length/2));
root.right=sortedArrayToBST(Arrays.copyOfRange(nums,nums.length/2+1,nums.length));
return root;
}
}