Find Mode in Binary Search Tree

easy tree bst dfs

Problem

Given the root of a BST that may contain duplicates, return every value that occurs most frequently. Try to use O(1) extra space (not counting recursion stack).

Inputroot = [1,null,2,2]
Output[2]
2 appears twice, 1 once. Mode is 2.

def find_mode(root):
    modes, max_count, count, prev = [], 0, 0, None
    def inorder(node):
        nonlocal max_count, count, prev
        if not node: return
        inorder(node.left)
        count = count + 1 if node.val == prev else 1
        if count > max_count:
            max_count, modes[:] = count, [node.val]
        elif count == max_count:
            modes.append(node.val)
        prev = node.val
        inorder(node.right)
    inorder(root)
    return modes
function findMode(root) {
  let modes = [], maxCount = 0, count = 0, prev = null;
  function inorder(node) {
    if (!node) return;
    inorder(node.left);
    count = node.val === prev ? count + 1 : 1;
    if (count > maxCount) { maxCount = count; modes = [node.val]; }
    else if (count === maxCount) modes.push(node.val);
    prev = node.val;
    inorder(node.right);
  }
  inorder(root);
  return modes;
}
class Solution {
    List<Integer> modes = new ArrayList<>();
    int maxCount = 0, count = 0;
    Integer prev = null;
    public int[] findMode(TreeNode root) {
        inorder(root);
        int[] r = new int[modes.size()];
        for (int i = 0; i < r.length; i++) r[i] = modes.get(i);
        return r;
    }
    void inorder(TreeNode n) {
        if (n == null) return;
        inorder(n.left);
        count = (prev != null && n.val == prev) ? count + 1 : 1;
        if (count > maxCount) { maxCount = count; modes.clear(); modes.add(n.val); }
        else if (count == maxCount) modes.add(n.val);
        prev = n.val;
        inorder(n.right);
    }
}
class Solution {
    vector<int> modes;
    int maxCount = 0, count = 0;
    int prev = INT_MIN; bool first = true;
public:
    vector<int> findMode(TreeNode* root) { inorder(root); return modes; }
    void inorder(TreeNode* n) {
        if (!n) return;
        inorder(n->left);
        count = (!first && n->val == prev) ? count + 1 : 1;
        first = false;
        if (count > maxCount) { maxCount = count; modes = { n->val }; }
        else if (count == maxCount) modes.push_back(n->val);
        prev = n->val;
        inorder(n->right);
    }
};
Time: O(n) Space: O(h) recursion + answer