leetcode 669
题目链接
trim BST树,保证all节点都在区间[a, b]
中
相关题目:leetcode 450 解答
思路:
- 不止删除1个节点,会需要改树的结构
- delete node通过直接将其父节点的指针指向该node的左右孩子实现
- 递归返回的是修建完毕后的子树的根节点
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null)
return null;
if (root.val < low) { //左子树all 节点全部删除
TreeNode temp = trimBST(root.right, low, high);
return temp;
}
if (root.val > high) {
TreeNode temp = trimBST(root.left, low, high);
return temp;
}
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}
leetcode 108
题目链接
用有序数组构造BST,左右子树差 ≤ 1 \le 1 ≤1
思路:
- 利用递归的思想
- ∵ \because ∵ 数组有序,所以数组中间值是当前根节点
- 然后分别递归构建左子树和右子树
- 注意区间定义需统一,下面代码中定义为左闭右开
[left, right)
class Solution {
TreeNode root;
public TreeNode sortedArrayToBST(int[] nums) {
if (nums.length == 0)
return null;
root = buildTree(root, nums, 0, nums.length);
return root;
}
public TreeNode buildTree(TreeNode root, int[] nums, int begin, int end) {
if (begin == end)
return null;
int middle = (begin + end) >> 1;
root = new TreeNode(nums[middle]);
root.left = buildTree(root.left, nums, begin, middle);
root.right = buildTree(root.right, nums, middle + 1, end);
return root;
}
}
leetcode 538
题目链接
把BST树的每个节点全部转换成原始比他大的 all node 的和
思路:
- 双指针
- 注意遍历顺序怎样合适
- right - middle - left 合适
- 每次
更新的val = 上一个节点的val + 当前的val
![](https://i-blog.csdnimg.cn/blog_migrate/3fc790fb94a3c5b68dd4c471c817d1ed.png)
class Solution {
int pre = 0;
public TreeNode convertBST(TreeNode root) {
convert(root);
return root;
}
public void convert(TreeNode root) {
if (root == null)
return;
convert(root.right);
root.val += pre;
pre = root.val;
convert(root.left);
}
}