Skip to main content
LeetCode 1361, Medium. Topics: Tree, Depth-First Search, Breadth-First Search, Union Find, Graph. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:

Problem

You have <code>n</code> binary tree nodes numbered from <code>0</code> to <code>n - 1</code> where node <code>i</code> has two children <code>leftChild[i]</code> and <code>rightChild[i]</code>, return <code>true</code> if and only if all the given nodes form <strong>exactly one valid binary tree</strong>. If node <code>i</code> has no left child then <code>leftChild[i]</code> will equal <code>-1</code>, similarly for the right child. Note that the nodes have no values and that we only use the node numbers in this problem.

Examples

Constraints

  • n == leftChild.length == rightChild.length
  • 1 <= n <= 10^4
  • -1 <= leftChild[i], rightChild[i] <= n - 1

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026