首页 > 其他分享 >代码随想录 第21天 | ● 530.二叉搜索树的最小绝对差 ● 501.二叉搜索树中的众数 ● 236. 二叉树的最近公共祖先

代码随想录 第21天 | ● 530.二叉搜索树的最小绝对差 ● 501.二叉搜索树中的众数 ● 236. 二叉树的最近公共祖先

时间:2024-03-15 21:56:06浏览次数:23  
标签:return cur int 随想录 二叉 搜索 TreeNode null root

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

思路:判断最小绝对差,肯定用中序遍历,双指针一前一后依次判断。

class Solution {
    int result = Integer.MAX_VALUE;
    TreeNode pre = null;

    public int getMinimumDifference(TreeNode root) {
        if(root == null) return  0;
        getmin(root);
        return  result;
    }

    private void getmin(TreeNode cur) {
        if(cur == null) return ;
        //中序
        getmin(cur.left);

        if(pre != null){
            result = Math.min(result,Math.abs(pre.val-cur.val));
        }
        pre = cur;
        getmin(cur.right);
    }
}

leetcode:501. 二叉搜索树中的众数 - 力扣(LeetCode)

思路:二叉搜索树,中序遍历,找众数,可能有多个,所以要找到最大出现次数,当MAx找到时,再一一和count比对,一样就放到数组里。还是用了双指针查找,前后cur相同++,不相同重新计数

class Solution {
    ArrayList<Integer> arrayList = new ArrayList<>();
    TreeNode pre = null;
    int Maxcount = 0;
    int count = 0;
    public int[] findMode(TreeNode root) {
        if( root == null) return  null;
        getMode(root);
        int [] res = new int[arrayList.size()];
        for(int i = 0 ;i < res.length; i++){
            res[i] = arrayList.get(i);
        }
        return res;
    }

    private void   getMode(TreeNode cur) {

        if( cur == null) return;
        getMode(cur.left);
        int val = cur.val;
        //计数
        if (pre == null || val != pre.val) {
            count = 1;
        } else {
            count++;
        }
        //更新max
        if(count > Maxcount){
            Maxcount = count;
            arrayList.clear();
            arrayList.add(cur.val);
        }else if (count == Maxcount){
            arrayList.add(cur.val);
        }
        pre = cur;
        getMode(cur.right);
        return;

    }
}

普通二叉数:随便遍历二叉数,将所有出现值放入map里,出现一次+1,最后遍历找出最高频率的数。

class Solution {
    public int[] findMode(TreeNode root) {
        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> list = new ArrayList<>();
        if (root == null) return list.stream().mapToInt(Integer::intValue).toArray();
        // 获得频率 Map
        searchBST(root, map);
        List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream()
                .sorted((c1, c2) -> c2.getValue().compareTo(c1.getValue()))
                .collect(Collectors.toList());
        list.add(mapList.get(0).getKey());
        // 把频率最高的加入 list
        for (int i = 1; i < mapList.size(); i++) {
            if (mapList.get(i).getValue() == mapList.get(i - 1).getValue()) {
                list.add(mapList.get(i).getKey());
            } else {
                break;
            }
        }
        return list.stream().mapToInt(Integer::intValue).toArray();
    }

    void searchBST(TreeNode curr, Map<Integer, Integer> map) {
        if (curr == null) return;
        map.put(curr.val, map.getOrDefault(curr.val, 0) + 1);
        searchBST(curr.left, map);
        searchBST(curr.right, map);
    }

}

leetcode:236. 二叉树的最近公共祖先 - 力扣(LeetCode)

思路:后序遍历,因为要看左右节点的情况才能做判断,判断节点三种情况,什么是递归回溯,就是能够一直到二叉数的最深处,这是递归,如果出现满足三种情况的任一一种,就返回根节点,这是回溯

1.

//两节点都不为空,说明pq都找到了。

2.

//左不为空,说明左孩子找到p或q了

3. 

//说明右孩子找到p或q了
class Solution {
    
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return null;
        //后序
        TreeNode left = lowestCommonAncestor(root.left,p,q);
        TreeNode right = lowestCommonAncestor(root.right,p,q);
        if(root == p || root == q) return root;
        //两节点都不为空,说明pq都找到了。
        if(left != null && right != null){
            return  root;
        }else if(left != null && right == null) return left;//说明左孩子找到p或q了
        else if(left == null && right != null) return right;//说明右孩子找到p或q了
        else return  null; //都没找到

    }
}

 

标签:return,cur,int,随想录,二叉,搜索,TreeNode,null,root
From: https://www.cnblogs.com/lengbo/p/18076139

相关文章

  • 通关代码随想录!!!
    60天的坚持,52篇博客,142道力扣题,自己还是做到了......
  • 【leetcode】二叉树的前序遍历➕中序遍历➕后序遍历
    大家好,我是苏貝,本篇博客带大家刷题,如果你觉得我写的还不错的话,可以给我一个赞......
  • 力扣刷题Days19-637.二叉树的层平均数
    目录1,题目2,代码2.1广度优先遍历2.2深度优先遍历3,学习与总结1,题目给定一个非空二叉树的根节点 root ,以数组的形式返回每一层节点的平均值。2,代码2.1广度优先遍历/***Definitionforabinarytreenode.*functionTreeNode(val,left,right){*......
  • 二叉查找树/堆 /Treap/Spaly树串联分析
    二叉查找树(BST)二叉查找树:中序遍历是一个递增的序列。父节点的左子树的所有结点都比父节点小,父节点右子树的结点比父节点都大。在一颗随机构造的BST上,查找一个元素的时间复杂度位O(logn),但是如果我们有序的插入结点,那么BST的高度将位N,时间复杂度位O(n)。importjava.util.Sc......
  • 洛谷题单指南-二叉树-P1030 [NOIP2001 普及组] 求先序排列
    原题链接:https://www.luogu.com.cn/problem/P1030题意解读:已知中序、后序,求先序。解题思路:与洛谷题单指南-二叉树-P1827[USACO3.4]美国血统AmericanHeritage非常类似,不在介绍过程,直接给出代码。100分代码:#include<bits/stdc++.h>usingnamespacestd;stringin,post......
  • 二叉树的垂序遍历
    说在前面......
  • 用A*算法设计搜索策略,补全关于下列走迷宫问题的程序
    补全下列关于走迷宫的程序:classNode():#TODO:完成结点类的定义,结点中要包含状态、父结点、算符等必要成员。根据算法需求,还可能包含该结点的路径代价、启发函数值、估计代价等信息def__init__(self,state,parent,action,stepCost,hCost):self.st......
  • L2-3 二叉搜索树的2层结点统计
    L2-3二叉搜索树的2层结点统计分数25作者陈越单位浙江大学二叉搜索树或者是一棵空树,或者是具有下列性质的二叉树:若它的左子树不空,则左子树上所有结点的值均小于或等于它的根结点的值;若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;它的左、右子树也分别为二叉......
  • 代码随想录算法训练营第四十七天| ● 198.打家劫舍 ● 213.打家劫舍II ● 337.打家
    打家劫舍 题目链接:198.打家劫舍-力扣(LeetCode)思路:每一家的最大收益来源只有两个,一个是这家不偷,那么最大收益等于从上一家出来的最大收益,另一个是偷这一个家,因此最大收益等于从上上一家出来的最大收益加这一家的收益。classSolution{public:introb(vector<int>&nu......
  • 代码随想录算法训练营第四十七天 | 337.打家劫舍III,213.打家劫舍II ,198.打家劫舍
     198.打家劫舍 已解答中等 相关标签相关企业 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。给定一......