代码随想录训练营二刷第二十三天 | 669. 修剪二叉搜索树 108.将有序数组转换为二叉搜索树 538.把二叉搜索树转换为累加树
一、669. 修剪二叉搜索树
题目链接:https://leetcode.cn/problems/trim-a-binary-search-tree/
思路:当前节点小于low递归处理右子树,当前节点大于high递归处理左子树。
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.将有序数组转换为二叉搜索树
题目链接:https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/
思路:划分区间,二分划分
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return create(nums, 0, nums.length-1);
}
TreeNode create(int[] nums, int left, int right) {
if (left > right) return null;
int mid = left + (right - left)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = create(nums, left, mid - 1);
root.right = create(nums, mid + 1, right);
return root;
}
}
三、 538.把二叉搜索树转换为累加树
题目链接:https://leetcode.cn/problems/convert-bst-to-greater-tree/
思路:按照右中左来遍历,最大值就他自己,第二个就是前一个值加他的值。
class Solution {
TreeNode pre = null;
public TreeNode convertBST(TreeNode root) {
forTree(root);
return root;
}
void forTree(TreeNode root) {
if (root == null)return;
forTree(root.right);
if (pre != null) {
root.val += pre.val;
}
pre = root;
forTree(root.left);
}
}