当前位置:网站首页>LeetCode 501 :二叉搜索樹中的眾數

LeetCode 501 :二叉搜索樹中的眾數

2022-06-10 23:35:00 斯沃福德

二叉搜索樹中的眾數

題目:

在這裏插入圖片描述

思路:

使用pre節點和root節點進行比較
用count來記錄節點值重複的次數
①先確定count值才能確定是否添加root值
若pre為null,或者pre和root值不等時 則開始記數;如果pre和root等則count++累加
②用count和max比較,如果count比max大,則之前list存的都無效,清除list
若count=max,即有新的眾數出現,添加至list
若count<max,忽略

class Solution {
    
    int count=0;
    int max=Integer.MIN_VALUE;
    TreeNode pre=null;
    ArrayList<Integer> list;
    public int[] findMode(TreeNode root) {
    
        list=new ArrayList<>();
        check(root);
        int n=list.size();
        int[]r =new int[n];
        for(int i=0;i<n;i++){
    
            r[i]=list.get(i);
        }
        return r;

    }

    void check(TreeNode root){
    
        if(root==null){
    
            return;
        }
        check(root.left);
        //中序遍曆
        //開始記數,重新記數
        if(pre==null || pre.val!=root.val){
    
            count=1;
        }else if(root.val==pre.val){
    
            count++;
        }

    //存入結果
        if(count>max){
      // 若有重複的則只存count最高那個節點的值!
            list.clear();
            list.add(root.val);
            max=count;
        }else if(count==max){
    
            list.add(root.val);
        }
        //count<max則不存
        pre=root;
        check(root.right);
    }


}
原网站

版权声明
本文为[斯沃福德]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206102220542468.html