Leetcode刷题Day23--------------------二叉树
1. 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
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.left=trimBST(root.left,low,high);
root.right=trimBST(root.right,low,high);
return root;
}
}
2. 108.将有序数组转换为二叉搜索树
- 题目链接:https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/
- 文章链接: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
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return traversal(nums,0,nums.length-1);
}
//左闭右闭
public TreeNode traversal(int[] nums, int left, int right){
if(left>right) return null;
//以下三句都可
//int mid=(left+right)/2;
//int mid = left + ((right - left)/2);
int mid = left + ((right - left) >> 1);
TreeNode root=new TreeNode(nums[mid]);
root.left=traversal(nums,left,mid-1);
root.right=traversal(nums,mid+1,right);
return root;
}
}
3. 538.把二叉搜索树转换为累加树
- 题目链接:https://leetcode.cn/problems/convert-bst-to-greater-tree/
- 文章链接: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
遍历顺序:右中左-------------双指针(最小绝对差和众数也是这样的)
class Solution {
int sum=0;
public TreeNode convertBST(TreeNode root) {
traversal(root);
return root;
}
public void traversal(TreeNode cur){
if(cur==null) return;
traversal(cur.right);//右
sum += cur.val;//中
cur.val = sum;//中
traversal(cur.left);//左
}
}