一、669. 修剪二叉搜索树
题目链接:https://leetcode.cn/problems/trim-a-binary-search-tree/
文章讲解:https://programmercarl.com/0669.%E4%BF%AE%E5%89%AA%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91.html
视频讲解:https://www.bilibili.com/video/BV17P41177ud
1.1 初见思路
- 对于题目中的情况二应该如何处理?
1.2 具体实现
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) {
return null;
}
if (root.val < low) {
return trimBST(root.right, low, high);
}
if (root.val > high) {
return trimBST(root.left, low, high);
}
// root在[low,high]范围内
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}
1.3 重难点
二、 108.将有序数组转换为二叉搜索树
题目链接:https://leetcode.cn/problems/remove-element/
文章讲解:https://programmercarl.com/0108.%E5%B0%86%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84%E8%BD%AC%E6%8D%A2%E4%B8%BA%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91.html
视频讲解:https://www.bilibili.com/video/BV1uR4y1X7qL
2.1 初见思路
- 数组的中位数是根节点,左子树是中位数的左边的部分数组,同理,右子树是右侧的部分数组
- 递归的返回条件是什么?取决于你选定的区间是左闭右闭还是左闭右开。这里我们选择左闭右闭比较好
2.2 具体实现
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
TreeNode root = getNode(nums,0,nums.length-1);
return root;
}
public TreeNode getNode(int[] nums,int left,int right){
if(left>right){
return null;
}
int mid = left+(right-left)/2;
TreeNode node = new TreeNode(nums[mid]);
node.left = getNode(nums,left,mid-1);
node.right = getNode(nums,mid+1,right);
return node;
}
}
2.3 重难点
三、 538.把二叉搜索树转换为累加树
题目链接:https://leetcode.cn/problems/remove-element/
文章讲解:https://programmercarl.com/0538.%E6%8A%8A%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E8%BD%AC%E6%8D%A2%E4%B8%BA%E7%B4%AF%E5%8A%A0%E6%A0%91.html
视频讲解:https://www.bilibili.com/video/BV1d44y1f7wP
3.1 初见思路
- 利用二叉搜索树的特性解题
3.2 具体实现
class Solution {
int sum;
public TreeNode convertBST(TreeNode root) {
sum = 0;
convertBST1(root);
return root;
}
// 按右中左顺序遍历,累加即可
public void convertBST1(TreeNode root) {
if (root == null) {
return;
}
convertBST1(root.right);
sum += root.val;
root.val = sum;
convertBST1(root.left);
}
}