669. 修剪二叉搜索树
题目链接:669. 修剪二叉搜索树 - 力扣(LeetCode)
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if(root == null) {
return null;
}
if(root.val >= low && root.val <= high) {
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}else if(root.val < low) {
return trimBST(root.right, low, high);
}else {
return trimBST(root.left, low, high);
}
}
}
108.将有序数组转换为二叉搜索树
题目链接:108. 将有序数组转换为二叉搜索树 - 力扣(LeetCode)
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return helper(nums, 0, nums.length - 1);
}
private TreeNode helper(int[] nums, int start, int end) {
if(end < start) {
return null;
}
TreeNode root = new TreeNode(nums[(start + end)/2]);
root.left = helper(nums, start, (start + end)/2 - 1);
root.right = helper(nums, (start + end)/2 + 1, end);
return root;
}
}
538.把二叉搜索树转换为累加树
题目链接:538. 把二叉搜索树转换为累加树 - 力扣(LeetCode)
class Solution {
int val = 0;
public TreeNode convertBST(TreeNode root) {
if(root == null) {
return null;
}
convertBST(root.right);
root.val += val;
val = root.val;
convertBST(root.left);
return root;
}
}