文章目录
一、今日刷题
1.题目
- 将有序数组转换为二叉搜索树
跳转LeetCode
给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。
高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。
2.分析
本题比较简单,但是一开始想的方向不对,本打算将数组转换成列表,这样操作一个数,就删除一个,但是不好。关键就在于递归函数的思路错了。
得好好学习题解是怎么构建递归函数的,明确递归函数的功能:在数组内找到根节点,并以根节点为断点将数组分成两部分,分别构成根节点的左右子树,进行递归即可。(利用二叉搜索树中序遍历是递增序列的性质,给定递增序列,那么序列的中间值就是二叉树搜索的根节点)
base case 也值得参考,有时不一定就要以 root 作为 base case 的判断条件,要找递归函数中一直在变化并且变化到一定程度会导致递归函数无法继续进行的参数。
3.代码
答案代码:
package BinaryTree.BinarSearchTree;
import java.util.ArrayList;
import java.util.List;
/**
* @author: LYZ
* @date: 2022/3/18 15:55
* @description: 108. 将有序数组转换为二叉搜索树
*/
public class SortedArrayToBST {
public TreeNode sortedArrayToBST(int[] nums) {
TreeNode ans = construct(nums, 0, nums.length - 1);
return ans;
}
TreeNode construct(int[] nums, int left, int right) {
if (left > right) {
return null;
}
int rootPosition = (left + right) / 2;
TreeNode root = new TreeNode(nums[rootPosition]);
root.left = construct(nums, left, rootPosition - 1);
root.right = construct(nums, rootPosition + 1, right);
return root;
}
}