Validate Binary Tree Nodes - Problem
You're given n binary tree nodes numbered from 0 to n-1. Each node i has at most two children specified by arrays leftChild[i] and rightChild[i].
Your task is to determine whether these nodes form exactly one valid binary tree. A valid binary tree must satisfy:
- Single root: Exactly one node has no parent
- No cycles: Following parent-child relationships never loops back
- Connected: All nodes are reachable from the root
- Binary constraint: Each node has at most 2 children and at most 1 parent
If a node has no left or right child, the corresponding array value will be -1.
Example: nodes [0,1,2], leftChild = [1,-1,-1], rightChild = [2,-1,-1] forms tree: 0 โ {1, 2}
Input & Output
example_1.py โ Valid Binary Tree
$
Input:
n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]
โบ
Output:
true
๐ก Note:
Forms a valid tree: Node 0 is root with children 1 and 2, Node 2 has child 3. All nodes connected, no cycles, single root.
example_2.py โ Multiple Roots
$
Input:
n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]
โบ
Output:
false
๐ก Note:
Node 3 has two parents (nodes 1 and 2), violating the binary tree constraint that each node has at most one parent.
example_3.py โ Disconnected Components
$
Input:
n = 2, leftChild = [-1,-1], rightChild = [-1,-1]
โบ
Output:
false
๐ก Note:
Two nodes with no connections form two separate trees (forest), not a single binary tree.
Constraints
- 1 โค n โค 104
- leftChild.length == rightChild.length == n
- -1 โค leftChild[i], rightChild[i] โค n - 1
- A value of -1 means the node has no left/right child
Visualization
Tap to expand
Understanding the Visualization
1
Count Parents
Count how many parents each person has - valid tree has at most 1 parent per person
2
Find Ancestor
Identify the family ancestor - exactly one person should have no parents
3
Trace Lineage
Starting from ancestor, visit all descendants to ensure everyone is connected
4
Verify Completeness
Confirm that all family members were reached in the lineage trace
Key Takeaway
๐ฏ Key Insight: A valid binary tree has exactly n-1 edges (parent-child relationships) and forms a connected acyclic graph with a single root. Count in-degrees efficiently to validate structure before checking connectivity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code