★【二叉搜索树】【修剪二叉搜素树】Leetcode 669. 修剪二叉搜索树

★【二叉搜索树】【修剪二叉搜素树】Leetcode 669. 修剪二叉搜索树

---------------🎈🎈669. 修剪二叉搜索树 题目链接🎈🎈-------------------

解法1 递归 反复做吧

在这里插入图片描述


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

class Solution {  
    // 删除小于low 大于high的节点
    public TreeNode trimBST(TreeNode root, int low, int high) {
        
        if(root == null){
            return null;
        }

        // 如果当前节点小于low 那么就去继续递归当前节点的右子树(右子树可能大于low) 结果即为修剪后的当前节点的右子树 返回right(返回的就是右子树头结点)
        if(root.val < low){
            TreeNode right = trimBST(root.right, low, high);
            return right;
        }
        // 如果当前节点大于high 那么就去继续递归当前节点的左子树(左子树可能小于high) 结果即为修剪后的当前节点的左子树 返回left(返回的就是左子树头结点)
        if(root.val > high){
            TreeNode left =  trimBST(root.left, low, high);
            return left;
        }

        root.left = trimBST(root.left,low,high);
        root.right = trimBST(root.right,low,high);
        return root;

    }
}
           
    

相关推荐

  1. 669.修建搜索

    2024-03-15 06:40:02       30 阅读
  2. 算法题记录】669. 修剪搜索

    2024-03-15 06:40:02       29 阅读
  3. 算法复习|修剪搜索

    2024-03-15 06:40:02       41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-15 06:40:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-15 06:40:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-15 06:40:02       82 阅读
  4. Python语言-面向对象

    2024-03-15 06:40:02       91 阅读

热门阅读

  1. 华为认证云计算专家(HCIE-Cloud Computing)--判断题

    2024-03-15 06:40:02       41 阅读
  2. 如何降低云计算成本?

    2024-03-15 06:40:02       47 阅读
  3. 1005. K 次取反后最大化的数组和(力扣LeetCode)

    2024-03-15 06:40:02       40 阅读
  4. #LLM入门|Prompt#3.3_存储_Memory

    2024-03-15 06:40:02       40 阅读
  5. CRON 定时任务

    2024-03-15 06:40:02       38 阅读
  6. 【React 函数式组件知识点】

    2024-03-15 06:40:02       36 阅读
  7. CSS 3

    CSS 3

    2024-03-15 06:40:02      33 阅读