669. 修剪二叉搜索树
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
//递归到null 返回上一节点null
if(root == null) return root;
//当前节点小于区间最小值,递归当前节点右子树 返回剪枝后的节点
if(root.val < low){
TreeNode right = trimBST(root.right,low,high);
return right;
}
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;
}
}
108.将有序数组转换为二叉搜索树
思路:区间定义左边右闭 取有序数组中间值为根节点
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return soft(nums,0,nums.length - 1);
}
public TreeNode soft(int[] nums,int left,int right){
//区间定义左边右闭 left == right 表示一个节点属于合规范围 left > right 不合规
if(left > right){
return null;
}
//取有序数组中间值为根节点
int mid = (right - left) / 2 + left;
TreeNode root = new TreeNode(nums[mid]);
root.left = soft(nums,left,mid-1);
root.right = soft(nums,mid+1,right);
return root;
}
}
538.把二叉搜索树转换为累加树
思路:pre指针的使用技巧,二叉树:搜索树的最小绝对差 (opens new window)和二叉树:我的众数是多少?
class Solution {
public int pre = 0;
public TreeNode convertBST(TreeNode root) {
//累加树 反中序 遍历顺序。右中左 双指针比较
soft(root);
return root;
}
private void soft(TreeNode cur){
//遍历到最后
if(cur == null){
return;
}
//右
soft(cur.right);
cur.val += pre;
pre = cur.val;
soft(cur.left);
}
}