KatInterview

Identify Node Value Present Across Most Depth Levels

Trees & GraphsModel answer
MediumModel answerTrees & Graphstrees-graphsbreadth-first-searchhash-table

Last updated

Find the binary tree node value that appears across the highest number of unique depth levels.

Given the root of a binary tree whose nodes contain hashable values (e.g., characters or integers), determine which value is present across the maximum number of distinct depth levels.

For example, consider the following tree:

     X
    / \
   X   Y
  / \
 Z   Z
  • Value X appears at depth 0 (the root) and depth 1. Count of distinct levels = 2.
  • Value Y appears only at depth 1. Count of distinct levels = 1.
  • Value Z appears twice, but both occurrences are at depth 2. Count of distinct levels = 1.

The output for this tree should be 'X'.

Requirements

  1. Define clear rules for edge cases, such as an empty tree or ties between multiple values.
  2. Outline your algorithm, explain why it correctly tracks level counts, and state both time and memory complexities.
  3. Provide a working Python implementation.

Hints

Hint 1

Counting total node frequency is different from counting unique levels. Multiple occurrences of a value on the exact same depth level only count once.

Hint 2

If you use Breadth-First Search (BFS), nodes at depth `d` are processed sequentially before any node at depth `d + 1`.

Hint 3

Instead of storing a full set of visited levels for each value, can you track just the most recent level index at which a value was encountered?