Ctrl K

Listing in Preorder

Medium
A binary tree was exported to a list rows: each row [id, parent] holds a node number and the number of its parent (the root has parent = -1). Node numbers are distinct, and the rows really do form a binary tree, so every node has at most two children. The export does not say which child is left and which is right. Check whether the children can be arranged so that the order of rows is exactly a preorder traversal: the node first, then its whole left subtree, then its whole right subtree. Return True if it is possible and False otherwise.
Example 1
rows=[[7, -1], [3, 7], [5, 3], [1, 7]] → True

The root is 7 with children 3 and 1, and 3 has a child 5. The order 7 → 3 → 5 → 1 is a preorder: the whole subtree of 3 comes first, then 1.

Example 2
rows=[[7, -1], [3, 7], [1, 7], [5, 3]] → False

Node 1 shows up after 3 while the subtree of 3 (node 5) is still unfinished. No choice of left and right children gives this order.

Example 3
rows=[[4, -1]] → True
Constraints
  • 1 ≤ len(rows) ≤ 10⁵
  • rows[i] = [id, parent], 0 ≤ id ≤ 10⁵, -1 ≤ parent ≤ 10⁵
  • Node numbers are distinct
  • The rows form a binary tree with exactly one root
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree Into a Right Chain MediumTree From Bracket Notation MediumPair Across Two Search Trees MediumLeft, Node, Right EasyParent Before Children Easy
loading Python…
Input
rows=[[7, -1], [3, 7], [5, 3], [1, 7]]
Expected
True

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