代码随想录训练营第23天|669. 修剪二叉搜索树,108.将有序数组转换为二叉搜索树,538.把二叉搜索树转换为累加树
)
669.修剪二叉搜索树
文章
思路
看完题不太会
难点在于
1)如何搜索上下界
2)如何删除
代码随想录提供了两种做法
1)递归,如果根节点在区间内,则修剪左右子树;如果根节点值小于区间下确界,则返回左子树的修剪;如果根节点值大于区间上确界,则返回右子树的修剪。如果根节点为空则返回空。
2)迭代。首先移动root,使得root位于区间内。然后从根节点出发找下界,即如果发现当前节点的左孩子的值小于下界,则用左孩子的右孩子代替左孩子,直到当前的左孩子在区间内,才能更新当前的访问位置为左孩子。向右找上界同理。最终返回root。
代码
迭代法好理解,这里放迭代法
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
TreeNode cur;
while (root != null && (root.val > high || root.val < low)) {
if (root.val > high) {
root = root.left;
} else {
root = root.right;
}
}
cur = root;
while (cur != null) {
while (cur.left != null && cur.left.val < low) {
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.left;
}
cur = cur.right;
}
return root;
}
}
108.将有序数组转换为二叉搜索树
文章
思路
要求是平衡二叉搜索树
考虑从数组中间取根节点,递归用两侧数组分别构造左右子树
代码
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
int n = nums.length;
return construct(nums, 0, n);
}
public TreeNode construct(int[] nums, int start, int end) {
if (start < end) {
int mid = start + ((end - start) >> 1);
TreeNode root = new TreeNode(nums[mid]);
root.left = construct(nums, start, mid);
root.right = construct(nums, mid + 1, end);
return root;
} else{
return null;
}
}
}
538.把二叉搜索树转换为累加树
文章
思路
得到了双指针法的提示,不然也不容易想到
这是先右后左的中序遍历,全局变量指针pre维护上一个累加过的节点,递归中序遍历,将累加过的节点的值加到当前节点值上
代码
class Solution {
private TreeNode pre = null;
public TreeNode convertBST(TreeNode root) {
traversal(root);
return root;
}
public void traversal(TreeNode root) {
if (root == null) {
return;
}
traversal(root.right);
if (pre != null) {
root.val += pre.val;
}
pre = root;
traversal(root.left);
}
}
总结
不出意外的话是二叉树最后一天
感觉遍历二叉树仿佛是一切的基础
又要做题又要开会真的缺时间总结