LeetCode669 修剪二叉搜索树
题目链接:https://programmercarl.com/0669.%E4%BF%AE%E5%89%AA%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91.html代码:
public class code669 {
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;
}
}
LeetCode108 将有序数组转换为二叉搜索树
public class code108 {
public TreeNode sortedArrayToBST(int[] nums) {
return build(nums, 0, nums.length);
}
// 左闭右开
private TreeNode build(int[] nums, int left, int right) {
if (left >= right) {
return null;
}
int mid = (left + right) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = build(nums, left, mid);
root.right = build(nums, mid + 1, right);
return root;
}
}
LeetCode538 把二叉搜索树转换为累加树
public class code538 {
int pre = 0;
public TreeNode convertBST(TreeNode root) {
convert(root);
return root;
}
private void convert(TreeNode root) {
if (root == null) return;
// 遍历顺序为右中左,这样顺序是从大到小
convert(root.right);
root.val += pre;
pre = root.val;
convert(root.left);
}
}
从大到小更新节点
二叉树章节完结