【力扣刷题】Day21——二叉树专题


二叉树专题到此完结,后续再扩展刷题吧,上一篇文章:【力扣刷题】Day20——二叉树专题_塔塔开!!!的博客-CSDN博客

29. 修剪二叉搜索树

题目链接:669. 修剪二叉搜索树 - 力扣(LeetCode)

思路:利用二叉搜索树的性质进行递归遍历判断修剪即可。

Code

/**
    本题的关键在于:如果不符合条件的节点要修剪掉(删除),
    要是它的左/右子树还有符合情况的子树,要如何处理
 */
class Solution {
    
    
    public TreeNode trimBST(TreeNode root, int l, int r) {
    
    
        return dfs(root, l, r);
    }
    public TreeNode dfs(TreeNode root, int l, int r){
    
    
        if(root == null){
    
    
            return null;
        }
        if(root.val < l){
    
    // 递归去看它的右子树是否还有满足条件的情况
            TreeNode right = dfs(root.right, l, r);
            return right;// 返回满足条件的右子树
        }
        if(root.val > r){
    
    
            TreeNode left = dfs(root.left, l, r);
            return left;
        }
        // 遍历拼接: 将满足要求的子树进行拼接
        root.left = dfs(root.left, l, r);// root.left接入符合条件的左孩
        root.right = dfs(root.right, l, r);

        // 返回根节点
        return root;
    }
}

精简版:

/**
    本题的关键在于:如果不符合条件的节点要修剪掉(删除),
    要是它的左/右子树还有符合情况的子树,要如何处理
 */
class Solution {
    
    
    public TreeNode trimBST(TreeNode root, int l, int r) {
    
    
        return dfs(root, l, r);
    }
    public TreeNode dfs(TreeNode root, int l, int r){
    
    
        if(root == null){
    
    
            return null;
        }
        // 递归去看它的右子树是否还有满足条件的情况
        if(root.val < l) return dfs(root.right, l, r);
        if(root.val > r) return dfs(root.left, l, r);

        // 拼接
        root.left = dfs(root.left, l, r);
        root.right = dfs(root.right, l, r);

        return root;
    }
}

30. 将有序数组转换为二叉搜索树

题目链接:108. 将有序数组转换为二叉搜索树 - 力扣(LeetCode)

思路:利用二叉搜索树的性质,直接拿有序序列递归构建即可(中序为有序的—(根每次都是树的中心点,用中心为划分左右去区间的边界即可))

Code

class Solution {
    
    
    public TreeNode sortedArrayToBST(int[] nums) {
    
    
        return dfs(nums, 0, nums.length - 1);
    }
    // 利用有序序列构建二叉搜索树
    public TreeNode dfs(int[] nums, int l, int r){
    
    
        if(l > r){
    
    
            return null;
        }

        int mid = (l + r) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = dfs(nums, l, mid - 1);// 这里是mid - 1而不是mid(不包含根)
        root.right = dfs(nums, mid + 1, r);

        return root;
    }
}

31. 把二叉搜索树转换为累加树

题目链接:538. 把二叉搜索树转换为累加树 - 力扣(LeetCode)

思路:当位于某一个节点,转换为累计数(加上自己 和 比他大的节点值),要找大于它的,那么我们就可以先遍历右子树(二叉搜索性质),然后对根节点进行操作,并不断更新当前遍历到的节点的节点值,即可得到题目要求的累加树,那么本题的遍历顺序就是:右 根 左

Code

class Solution {
    
    
    public TreeNode convertBST(TreeNode root) {
    
    
        return dfs(root);
    }

    int sum = 0;// 记录当前节点右边比他大的所有节点和(全局)
    public TreeNode dfs(TreeNode root){
    
    
        if(root == null){
    
    
            return null;
        }

        // 右根左
        dfs(root.right);
        root.val += sum;
        sum = root.val;
        dfs(root.left);

        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_54773252/article/details/127271557