Ctrl K

Tree From Parent Links

Medium
A binary tree whose node values are all distinct is described by a list links. Each link [parent, child, side] says that the node with value child is a child of the node parent: - if side == 1, it is the left child; - if side == 0, it is the right child. Every edge of the tree is described by exactly one link, and the links come in no particular order. Rebuild the tree and return its root.
Example 1
links=[[7, 3, 0], [12, 7, 1], [12, 9, 0], [3, 5, 1]] → [12, 7, 9, None, 3, None, None, 5]

The value 12 never appears as a child, so it is the root. Its left child is 7 and its right child is 9; 7 has 3 on the right, and 3 has 5 on the left.

Example 2
links=[[4, 8, 1]] → [4, 8]

A single link: root 4 with left child 8.

Example 3
links=[[2, 6, 0], [6, 1, 0], [6, 11, 1], [2, 30, 1]] → [2, 30, 6, None, None, 11, 1]
Constraints
  • 1 ≤ len(links) ≤ 3 · 10⁴
  • links[i] = [parent, child, side]
  • 1 ≤ parent, child ≤ 10⁵, side ∈ {0, 1}
  • The links describe one valid binary tree
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree From Pre-Order and In-Order Walks MediumTree From In-Order and Post-Order Walks MediumPath Totals in a Coded Tree MediumTree From Pre-Order and Post-Order Walks MediumPreorder of a Search Tree Medium
loading Python…
Input
links=[[7, 3, 0], [12, 7, 1], [12, 9, 0], [3, 5, 1]]
Expected
[12, 7, 9, None, 3, None, None, 5]

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