669. 修剪二叉搜索树
题目链接/文章讲解: 代码随想录
思路想不到
迭代
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;
}
}
108.将有序数组转换为二叉搜索树
利用中点
迭代
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return getsortedArrayToBST(nums, 0, nums.length - 1);
}
public TreeNode getsortedArrayToBST(int[]nums, int left, int right) {
if(left > right) return null;//终止条件 左闭右闭
int mid = left + ((right - left) >> 1);//中点
TreeNode root = new TreeNode(nums[mid]);
root.left = getsortedArrayToBST(nums, left, mid - 1);
root.right = getsortedArrayToBST(nums, mid + 1, right);
return root;
}
}
538.把二叉搜索树转换为累加树
思路想不到
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);//左
}
}