leetcode 669. 修剪二叉搜索树
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);
} else if (root.val < low) {
// 如果当前节点超出了左边界,可能bst的有边界还存在符合条件的值,所以要去右边界遍历
// 因为当前节点需要被删除,所以当前节点为遍历右孩子节点的返回值
root = trimBST(root.right, low, high);
} else if (root.val > high) {
// 同上
root = trimBST(root.left, low, high);
}
return root;
}
leetcode 108.将有序数组转换为二叉搜索树
题目给的是有序的数组,刚好二叉搜索树的中序遍历就说升序的;
每次遍历到当前的根节点时,其实就是获取当前的中间值,比左子树大,比右子树小。
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return buildBST(nums, 0, nums.length - 1);
}
public TreeNode buildBST(int[] nums, int left, int right) {
if (nums.length == 1) {
return new TreeNode(nums[0]);
}
if (left > right) {
return null;
}
int midIndex = left + (right - left) / 2;
TreeNode root = new TreeNode(nums[midIndex]);
root.left = buildBST(nums, left, midIndex - 1);
root.right = buildBST(nums,midIndex + 1, right);
return root;
}
}
leetcode 538.把二叉搜索树转换为累加树
通过中序遍历进行累加
class Solution {
int sum = 0;
public TreeNode convertBST(TreeNode root) {
if (root == null ) {
return null;
}
convertBST(root.right);
root.val = root.val + sum;
sum = root.val;
convertBST(root.left);
return root;
}
}