669 修剪二叉搜索树
https://leetcode.cn/problems/trim-a-binary-search-tree/description/
1,递归法,如果根超界,那么去修剪可能不超界的那一边返回,如果根不超界,左右子树修剪一下挂回根上返回根。修剪的过程是在每个节点处当它作为根超界时剪掉的,由于每个节点都会被判断,那么就处理了整棵树。
2, 迭代法,由于是BST不需要stack就可以迭代。先找到在界限以内的根,作为最后的返回值。两次迭代去砍掉伸的最远的超界的节点,当发现往左走要超界时,接管它的右孩子(右孩子可能有在界限内的),接管后继续判断上来的右孩子是不是超界,cur还不能往左继续走,所以这里用while而不是if.
class Solution { // recursion
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) return root;
if (root.val < low) {
return trimBST(root.right, low, high);
} else if (root.val > high) {
return trimBST(root.left, low, high);
} else {
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
}
return root;
}
}
class Solution { // iterative, BST不需要栈
public TreeNode trimBST(TreeNode root, int low, int high) {
while (root != null && (root.val < low || root.val > high)) {
if (root.val < low) { //先找到在区间里的根,这个根最后需要返回
root = root.right;
} else if (root.val > high) {
root = root.left;
}
}
if (root == null) return root;
TreeNode cur = root;
while (cur != null) {
while (cur.left != null && cur.left.val < low) { //cur.left要出左界了 // key while not if
cur.left = cur.left.right; //把出界的根拿掉接管它的右孩子
}
cur = cur.left;
}
cur = root;
while (cur != null) {
while (cur.right != null && cur.right.val > high) { //cur.right要出右界了
cur.right = cur.right.left; //把出界的根拿掉接管它的左孩子
}
cur = cur.right;
}
return root;
}
}
108 将有序数组转换为二叉搜索树
https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/description/
只写了递归法,“迭代法可以通过三个队列来模拟,一个队列放遍历的节点,一个队列放左区间下标,一个队列放右区间下标。”听起来好麻烦就先跳过了。
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return sortArrayToBST(nums, 0, nums.length -1);
}
private TreeNode sortArrayToBST(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 = sortArrayToBST(nums, left, mid - 1);
root.right = sortArrayToBST(nums, mid + 1, right);
return root;
}
}
538 把二叉搜索树转换为累加树
https://leetcode.cn/problems/convert-bst-to-greater-tree/description/
class Solution {
public TreeNode convertBST(TreeNode root) {
int[] sum = new int[1];
convertBST(root, sum);
return root;
}
private void convertBST(TreeNode root, int[] sum) {
if (root == null) return;
convertBST(root.right, sum);
root.val += sum[0];
sum[0] = root.val; // bug 不是 sum[0] += root.val, root.val已经被更新过为和了
convertBST(root.left, sum);
}
}