501. 二叉搜索树中的众数

深度优先搜索

class Solution {

    /**
     * 维护一个出现频率的最大值,如果频率等于最大值时就添加这个节点
     * 如果频率大于这个最大值,就清除已有的节点,更新最大值(二叉搜索树中序遍历,节点是排好序的)
     * 要和前一个节点比较大小,需要一个prev指针
     */
    ArrayList<Integer> list = new ArrayList<>();
    TreeNode prev;
    int count = 1;
    int max = 1;

    public int[] findMode(TreeNode root) {

        dfs(root);

        int[] res = new int[list.size()];
        int index = 0;

        for (int i = 0; i < res.length; i++) {
            res[i] = list.get(i);
        }

        return res;
    }

    public void dfs(TreeNode root){

        if (root == null){
            return;
        }

        dfs(root.left);

        /**
         * 如果和上一个节点相等,频率加1
         * 否则频率初始化为1
         */
        if (prev == null || prev.val != root.val){
            count = 1;
        }
        else {
            count++;
        }

        /**
         * 如果频率等于当前最大值,就添加进列表
         * 大于最大值,就要清空列表,更新最大值
         */
        if (max == count) {
            list.add(root.val);
        }
        else if (count > max){

            list.clear();
            list.add(root.val);
            max = count;
        }

        prev = root;

        dfs(root.right);
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

迭代

class Solution {

    public int[] findMode(TreeNode root) {

        ArrayList<Integer> list = new ArrayList<>();
        TreeNode prev = null;
        int count = 1;
        int max = 1;

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.isEmpty()){

            if (cur != null){

                stack.push(cur);
                cur = cur.left;
            }
            else {

                cur = stack.pop();

                if (prev == null || prev.val != cur.val){
                    count = 1;
                }
                else {
                    count++;
                }

                if (count == max){
                    list.add(cur.val);
                }
                else if (count > max){

                    list.clear();
                    list.add(cur.val);
                    max = count;
                }

                prev = cur;
                cur = cur.right;
            }
        }

        int[] res = new int[list.size()];
        int index = 0;

        for (int i = 0; i < res.length; i++) {
            res[i] = list.get(i);
        }

        return res;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/

posted @ 2022-02-24 10:50  振袖秋枫问红叶  阅读(24)  评论(0)    收藏  举报