Find Mode in Binary Search Tree

Given the root of a binary search tree (BST) with duplicates, return all the mode(s), i.e., the most frequently occurred element(s), in it.

If the tree has more than one mode, return them in any order.

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

Follow up: Could you do that without using any extra space? Assume that the implicit stack space incurred due to recursion does not count.

Example 1
    1
     \
      2
     /
    2
Inputroot = [1,null,2,2]
Output[2]
The value 2 appears most frequently in the tree.
Example 2
        0
Inputroot = [0]
Output[0]
The only value in the tree is 0, so it is the mode.

Constraints

  • The number of nodes in the tree is in the range [1, 10^4].
  • -10^5 <= Node.val <= 10^5

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate