Ctrl K

Most Frequent Values in a Search Tree

Easy
You are given the root of a binary search tree in which values may repeat. The ordering is non-strict: every value in a node's left subtree is less than or equal to the node's value, every value in its right subtree is greater than or equal to it, and each subtree follows the same rule. Find the values that occur in the tree most often. If several values tie, return all of them. The order of the answer does not matter. Try to do it without a dictionary of counts: the search-tree order lets you count repeats as you go (the recursion stack does not count as extra space).
Example 1
root=tree_node([6, 4, 8, 4, 6, None, 8, None, None, None, None, 8]) → [8]

The value 8 appears three times, while 4 and 6 appear twice each, so the answer is just 8.

Example 2
root=tree_node([3, 1, 5, 1, None, 5]) → [1, 5]

Both 1 and 5 appear twice and 3 only once. Both of the most frequent values go into the answer, in any order.

Example 3
root=tree_node([-7]) → [-7]
Constraints
  • 1 ≤ number of nodes ≤ 10⁴
  • -10⁵ ≤ Node.val ≤ 10⁵
  • The tree is a binary search tree as described above
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsNearest Value in a Search Tree EasyPair Sum in a Search Tree EasyClosest Pair in a Search Tree EasySearch Tree Into a Line EasyBand Sum in a Search Tree Easy
loading Python…
Input
root=tree_node([6, 4, 8, 4, 6, None, 8, None, None, None, None, 8])
Expected
[8]

Run checks the first 3 tests in your browser. Submit checks all 44 tests on the server, hidden ones included.