KatInterview

Leftmost and Rightmost Nodes per Depth from a Serialized Tree

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsbinary-treebfslevel-order

Last updated

Given a level-order serialized binary tree, return the first and last node value at each depth, testing BFS over an array-encoded tree and careful handling of null slots.

Silhouettes of a Binary Tree

You are given a binary tree encoded as a flat list in level-order form. Your task is to compute what is visible when the tree is looked at from its left edge and from its right edge.

Input encoding

The parameter tree is a list whose entries are integers or None:

  • The first entry is the root. If it is None (or the list is empty), the tree is empty.
  • Going through the non-null nodes in breadth-first order (top to bottom, left to right), each one takes the next two unread entries of the list as its left child and right child, in that order. A None entry means that child is absent.
  • A None entry does not take up any further entries for children of its own.
  • Trailing None entries may be left out. If the list ends before a node's child slots are filled, those missing children are absent.

For example, [1, 2, 3, None, 5, None, 4] describes this tree:

    1
   / \
  2   3
   \   \
    5   4

Task

Return a list of two lists, [left_view, right_view]:

  • left_view holds, for every depth from the root downward, the value of the leftmost node at that depth.
  • right_view holds, for every depth from the root downward, the value of the rightmost node at that depth.

Both lists are ordered from the top level to the bottom level. The leftmost node of a level is the one that appears first when that level is read left to right, regardless of whether it is a left or right child of its parent. If a level contains only one node, that value appears in both lists.

For an empty tree, return [[], []].

Constraints

  • The number of nodes in the tree is between 0 and 100.
  • Each node value is between -100 and 100.
  • The tree may be empty, a single node, or fully skewed (all left or all right children).
  • The returned value must be a list containing exactly two lists: the left view first, then the right view.

Examples

Example 1

Input: tree_silhouettes([1, 2, 3, None, 5, None, 4])

Output: [[1, 2, 5], [1, 3, 4]]

Example 2

Input: tree_silhouettes([1, None, 3])

Output: [[1, 3], [1, 3]]

Hints

Hint 1

The node you see from the left at a given depth is the first node of that level when read left to right; from the right it is the last one.

Hint 2

Run a breadth-first traversal one level at a time, taking a snapshot of the queue size at the start of each level so you know where the level ends.

Hint 3

You do not need to build node objects: keep a pointer into the input list and, each time you dequeue a non-null value, read the next two entries as its children (treating entries beyond the end of the list as absent).