二叉搜索树刷题

二叉搜索树的最小绝对差

题目

530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)

解题思路

二叉搜索树的中序遍历结果就是一个递增的序列,只需要中序遍历,然后不断判断相邻节点的差是否是最小值。

代码

int min = 100005;
    int pre = -1;
    public int getMinimumDifference(TreeNode root) {
        if(root==null)
            return -1;
        fun(root);
        return min;
    }

    private void fun(TreeNode root) {
        if(root==null)
            return;
        fun(root.left);
        System.out.println(root.val);
        if(pre==-1){
            pre = root.val;
        }else{
            min = Math.min(min, root.val-pre);
            pre=root.val;
        }
        fun(root.right);
    }

二叉树中第k个最小的元素

题目

230. 二叉搜索树中第K小的元素 - 力扣(LeetCode)

解题思路

基于中序遍历的序列,直接获取第k个元素即可

代码

public int kthSmallest(TreeNode root, int k) {
        if(root==null)
            return -1;
        List<Integer> list = new ArrayList<>();
        fun2(root,list);
        return list.get(k-1);
    }

    private void fun2(TreeNode root, List<Integer> list) {
        if(root==null)
            return;
        fun2(root.left,list);
        System.out.println(root.val);
        list.add(root.val);
        fun2(root.right,list);
    }

验证二叉搜索树

题目

98. 验证二叉搜索树 - 力扣(LeetCode)

解题思路

根据二叉搜索的特性

  • 节点的左子树只包含 小于 当前节点的数。
  • 节点的右子树只包含 大于 当前节点的数。
  • 所有左子树和右子树自身必须也是二叉搜索树。

代码

 public boolean isValidBST(TreeNode root) {
        return fun3(root,Long.MAX_VALUE,Long.MIN_VALUE);
    }

    private boolean fun3(TreeNode root, long maxValue, long minValue) {
        if(root==null)
            return true;
        if(root.val<=minValue||root.val>=maxValue){
            return false;
        }
        return fun3(root.left,root.val,minValue)&&fun3(root.right,maxValue,root.val);
    }

最近更新

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

    2024-07-13 11:06:05       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-13 11:06:05       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-13 11:06:05       57 阅读
  4. Python语言-面向对象

    2024-07-13 11:06:05       68 阅读

热门阅读

  1. Python实现音频均衡和降噪

    2024-07-13 11:06:05       20 阅读
  2. 深度学习之轻量化神经网络MobileNet

    2024-07-13 11:06:05       22 阅读
  3. 基于深度学习的RGB图像和IMU的数据融合

    2024-07-13 11:06:05       21 阅读
  4. F12打不开、打开后页面跳转、控制台持续刷新

    2024-07-13 11:06:05       20 阅读
  5. SQL注入:基于错误

    2024-07-13 11:06:05       20 阅读
  6. Python高级(四)_内存管理

    2024-07-13 11:06:05       26 阅读
  7. 菜单(Menu)

    2024-07-13 11:06:05       20 阅读
  8. QAbstractButton

    2024-07-13 11:06:05       20 阅读
  9. Fastadmin之 按钮触发弹窗

    2024-07-13 11:06:05       24 阅读