代码随想录day18 Java版

700.二叉搜索树中的搜索

前几天刚对比了下堆和二叉搜索树。堆是上下位置区分大小,二叉搜索树是左右位置区分大小

这道题简单应用了二叉搜索树的查找功能,直接用前序遍历

class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if (root.val ==val) return root;
        if (root.val > val && root.left != null ) return searchBST(root.left, val);
        if (root.val < val && root.right != null) return searchBST(root.right,val);
        return null;
    }
}

98.验证二叉搜索树

中序遍历下,输出的二叉搜索树节点的数值是从小到大的有序序列。

class Solution {
    List<Integer> res = new ArrayList<>();
    public boolean isValidBST(TreeNode root) {
        in(root);
        for (int i = 1; i < res.size(); i++) if (res.get(i) <= res.get(i-1)) return false;
        return true;
    }
    void in(TreeNode node) {
        if (node.left != null) in(node.left);
        res.add(node.val);
        if (node.right!= null) in(node.right);
    }
}

530.二叉搜索树的最小绝对差

跟上一题一样,遇到在二叉搜索树上求数值问题的题目,可以利用中序遍历把二叉搜索树转化为有序数组,再进行分析。

class Solution {
    List<Integer> res = new ArrayList<>();
    public int getMinimumDifference(TreeNode root) {
        in(root);
        int ans = 100000;
        for (int i = 1; i < res.size(); i++) ans = Math.min(ans,res.get(i)-res.get(i-1));
        return ans;
    }
    void in(TreeNode node) {
        if (node.left != null) in(node.left);
        res.add(node.val);
        if (node.right!= null) in(node.right);
    }
}

501.二叉搜索树中的众数

将节点放到map中,找到最大出现次数并按照该值找到众数

res.stream().mapToInt(Integer::intValue).toArray();实现ArrayList转数组

class Solution {
    Map<Integer, Integer> count = new HashMap<>();
    List<Integer> res = new ArrayList<>();
    public int[] findMode(TreeNode root) {
        in(root);
        int p = 0;
        for (int i : count.values()) p = Math.max(p,i);
        for (int i : count.keySet()) {
            if (count.get(i) == p) res.add(i);
        }
        return res.stream().mapToInt(Integer::intValue).toArray();
    }
    void in(TreeNode node) {
        if (node.left != null) in(node.left);
        count.put(node.val,count.getOrDefault(node.val,0)+1);
        if (node.right!= null) in(node.right);
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值