KatInterview

Tallest Chain of Nodes in an Index-Linked Binary Tree

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsbinary-treedfsiterative-traversal

Last updated

Compute the height of a binary tree given as a child-index table, handling empty input and very deep skewed trees without recursion failures.

Tallest Chain of Nodes in an Index-Linked Binary Tree

You are given a binary tree stored as a table of child indices. Your job is to report its height, measured as the number of nodes on the longest downward path that starts at the root and ends at a leaf.

Input format

The argument child_table is a list of [left, right] pairs.

  • Nodes are numbered 0 to n - 1, where n is the length of the list.
  • Row i holds the identifiers of node i's left child and right child.
  • The value -1 means that the child does not exist.
  • When the list is not empty, node 0 is the root.

Task

Implement tree_height(child_table) and return a single integer: the count of nodes along the longest path from the root down to a leaf.

  • An empty list describes an empty tree, and the answer is 0.
  • A tree consisting of just the root has answer 1.

Constraints

  • 0 <= n <= 200000
  • The table always describes one valid binary tree: every node can be reached from node 0, there are no cycles, and every node other than the root has exactly one parent.
  • Each child entry is either -1 or a valid node identifier.
  • The tree can be extremely lopsided, for example a single chain of 200000 nodes, so your approach must cope with very deep trees.
  • Aim for O(n) time.

Examples

Example 1

Input: tree_height([[1, 2], [-1, -1], [3, -1], [-1, -1]])

Output: 3

Example 2

Input: tree_height([])

Output: 0

Hints

Hint 1

Height counts nodes, not edges: the root alone has height 1 and an empty tree has height 0.

Hint 2

Each node's level is its parent's level plus one, so you can carry the level along while you traverse and keep the largest value seen.

Hint 3

A chain of 200000 nodes will exceed Python's default recursion limit, so use an explicit stack (or a queue) instead of recursive calls.