Validate That Parent and Child Links Form One Binary Tree

Last updated: November 29, 2026

Quick Overview

Given n nodes and arrays left and right where left[i] and right[i] are the children of node i (or -1 for none), return True only if all the links together form exactly one valid binary tree.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Phone Screen
Coding & Algorithms
Easy

0

0

0 solved


Given n nodes and arrays left and right where left[i] and right[i] are the children of node i (or -1 for none), return True only if all the links together form exactly one valid binary tree.

This shows up in Google screens around serialized structures, such as validating a tree loaded from a config or a protobuf. The interviewer looks for the three failure modes (a node with two parents, a cycle, or a forest) and a clean way to check all three in one pass.

What the Interviewer Expects
  • Names all three invalid shapes explicitly
  • Rejects any node that gets a second parent
  • Uses union-find to detect a cycle when linking parent and child
  • Requires exactly one component at the end
  • Traces a small failing example
Key Topics to Cover
Union-Find
Trees
Cycle Detection
Validation
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Return the root index instead of a boolean.
  • How would you do this with in-degree counting and a BFS instead?
  • What if the input is a generic n-ary tree as a list of edges?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: n, arrays left and right of length n with values in -1..n-1.
  • Valid means one connected structure, every node has at most one parent, exactly one node has none, and there are no cycl...
High-Level Design

Walk every parent-to-child link. Mark the child as having a parent; if it already had one, fail. Then union parent and child; if they are already in the same set the link closes a cycle, so fail. Each...


Submit Your Answer
Markdown supported