代码随想录day21| 669. 修剪二叉搜索树 、 108.将有序数组转换为二叉搜索树 、538.把二叉搜索树转换为累加树
669. 修剪二叉搜索树
思路
遍历二叉搜索树
如果当前节点小于范围的最小值,则递归寻找右子树中符合范围的根节点;
如果当前节点大于范围的最大值,则递归寻找左子树中符合范围的根节点;
左右递归的返回值赋给左右子树;
最后将root返回
class Solution {
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;
}
}
108.将有序数组转换为二叉搜索树
思路
- 首先找到数组的中间元素,当作根节点
- 然后把数组风格为左右两个;
- 将左右两个数组递归传入,得到的返回值赋给根节点的左右子树;
- 递归推出的条件是:当前数组若为null,返回null;当前数组大小若为1,则返回一个值为nums[0]的node节点,供上一层的子树接收;
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums == null){
return null;
}
if(nums.length == 1){
return new TreeNode(nums[0]);
}
int mid = nums.length/2;
TreeNode root = new TreeNode(nums[mid]);
int[] numsLeft = null;
int[] nullRight = null;
if(mid > 0){
numsLeft = new int[mid];
for(int i = 0 ; i < mid; i++){
numsLeft[i] = nums[i];
}
}
if(mid < nums.length-1){
nullRight = new int[nums.length-mid-1];
int j = 0;
for(int i = mid+1 ; i < nums.length; i++){
nullRight[j++] = nums[i];
}
}
root.left = sortedArrayToBST(numsLeft);
root.right = sortedArrayToBST(nullRight);
return root;
}
}
538.把二叉搜索树转换为累加树
思路
- 首先遍历二叉搜索树,计算所有数值总和sum
- 中序遍历二叉搜索树,处理中是,记录上一个节点的值,并且把当前节点的值修改为sum-前一个节点的值,然后更新sum;
- 最后返回root节点
class Solution {
TreeNode pre = null;
int sum = 0;
public TreeNode convertBST(TreeNode root) {
sum = getSum(root);
return convert(root);
}
public int getSum(TreeNode root) {
if(root == null){
return 0;
}
int left = getSum(root.left);
int right = getSum(root.right);
return left + right + root.val ;
}
public TreeNode convert(TreeNode root) {
if(root == null){
return null;
}
convert(root.left);
if(pre == null){
pre = new TreeNode();
pre.val = 0;
}
int n = root.val;
root.val = sum - pre.val;
pre.val = n;
sum = root.val;
convert(root.right);
return root;
}
}