← Questions

Build a binary tree from parent-child descriptions

0
AmazonCodingLast asked Mar 2026

A coding interview question asked in Amazon's technical phone screen, last asked Mar 2026. It tests trees and hash maps.

Each description is [parent, child, is_left]: child is the left child of parent when is_left is 1, the right child when it is 0. The descriptions together describe one binary tree with unique values, but they come in any order, so a node can appear as a child before it appears as a parent. Build the tree and return its root.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • build_tree(descriptions: list[list[int]]) -> TreeNode — TreeNode has val, left and right.

Example

descriptions = [[20, 15, 1], [20, 17, 0], [50, 20, 1], [50, 80, 0], [80, 19, 1]]
build_tree(descriptions)  ->  root 50

        50
       /  \
     20    80
    /  \   /
  15   17 19

descriptions = [[1, 2, 1], [2, 3, 0], [3, 4, 1]]
build_tree(descriptions)  ->  root 1     # 1 -> left 2 -> right 3 -> left 4

Constraints

  • 1 <= len(descriptions) <= 10^5; values are unique 32-bit integers.
  • The input describes exactly one valid tree: each child has one parent and each side of a parent is used at most once.

Clarifying questions

  • Are descriptions ordered? (No.)
  • How is the root identified? (The only value never listed as a child.)
  • Can the input contain contradictions or cycles?

What a strong answer covers

  • A map from value to node, creating each node the first time its value appears, so the same node is reused.
  • A set of child values; the root is the one node not in it.
  • O(n) time and space, with no dependence on input order.
  • Tests: a single description, a chain, children listed before parents.

Follow-ups

  • Reject bad input: a child with two parents, a side used twice, several roots.
  • Detect a cycle.
  • Build the tree incrementally and report the current roots after each description.

Where it's asked

  • Amazon · Technical phone screen · Last asked Mar 202660 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI

What it tests

trees · hash maps

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding