501. 二叉搜索樹中的衆數(樹)(BST)(回看)

在這裏插入圖片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private List<Integer> list = new LinkedList<>();
    private TreeNode pre = null;
    private int curfreq =0;
    private int maxfreq = 0;
    public int[] findMode(TreeNode root) {

        inOrder(root);

        int[] res = new int[list.size()];
        //System.out.print(maxfreqNum);
        
        for(int i = 0;i<list.size();i++){
            res[i] = list.get(i);
        }

        return res;
    }
    public void inOrder(TreeNode root){
        if(root == null) return;
        inOrder(root.left);
        
        if(pre!=null&&pre.val == root.val){
            curfreq++;
        }

        //在中序首結點和遍歷到pre.val != root.val時 重置curfreq =1;
        else{
            curfreq =1;
        }
        if(curfreq == maxfreq){
            list.add(root.val);
        }
        else if(curfreq>maxfreq){
            maxfreq =curfreq;
            //只存儲衆數集
            list.clear();
            list.add(root.val);
        }
        pre = root;

        inOrder(root.right);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章