二叉搜索树中的众数 (Find Mode in Binary Search Tree)

 

思路:

// @Title: 二叉搜索树中的众数 (Find Mode in Binary Search Tree)
// @Author: qisiii
// @Date: 2024-09-16 16:19:59
// @Runtime: 0 ms
// @Memory: 43.9 MB
// @comment: 
// @flag: 
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
    int cur , count = 0, max = 0;
    List<Integer> result = new ArrayList<>();

    public int[] findMode(TreeNode root) {
        dfs(root);
        int[] arr = new int[result.size()];
        for (int i = 0; i < result.size(); i++) {
            arr[i] = result.get(i);
        }
        return arr;
    }

    private void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root.left);
        if (root.val==cur) {
            count++;
        }else {
            cur = root.val;
            count = 1;
        }
        if (count == max) {
                result.add(cur);
            } else if (count > max) {
                max = count;
                result.clear();
                result.add(cur);
            }
        dfs(root.right);
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18