Day 20 - Leetcode 669修剪二叉搜索树 | Leetcode 108将有序数组转换为二叉搜索树 | Leetcode 538把二叉搜索树转换为累加树

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
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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值