Find Mode in Binary Search Tree

Given the `root` of a binary search tree (BST) with duplicates, return all the mode(s) (the most frequently occurring values) in it. If the tree has more than one mode, return them in any order. In this BST, the left subtree of a node holds only values less than or equal to the node, and the right subtree holds only values greater than or equal to it.

30:00

Find Mode in Binary Search Tree
easy
Free written solution
Topics
Companies

Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (the most frequently occurring values) in it. If the tree has more than one mode, return them in any order.

In this BST, the left subtree of a node holds only values less than or equal to the node, and the right subtree holds only values greater than or equal to it.

Example 1:
Input: {"root":[1,null,2,2]}
Output: [2]
Constraints:
  • The number of nodes in the tree is in the range [1,104][1, 10^4].

  • −105≤Node.val≤105-10^5 \leq \text{Node.val} \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,null,2,2]}

An inorder walk of a BST meets its values in sorted order, so equal values arrive back to back. Track the current run length and the longest run seen.

122inorder = sorted, equal values side by side

prev

None

count

0

best

0

modes

empty

open calls

none

current node / live run
open inorder calls
visited
run of a current mode
Variables
VariableValue
nodenull
prevNone
count0
best0
modes[]
DepthFunction Call
Stack empty
0/10