Validate Binary Tree Nodes - Problem
You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i]. Return true if and only if all the given nodes form exactly one valid binary tree.
If node i has no left child then leftChild[i] will equal -1, similarly for the right child.
Note: The nodes have no values and we only use the node numbers in this problem.
Input & Output
Example 1 — Valid Tree
$
Input:
leftChild = [1,-1,0,-1], rightChild = [-1,2,-1,-1]
›
Output:
false
💡 Note:
Node 3 is the only root. Nodes 0,1,2 form a cycle: 0→1→2→0, making node 3 disconnected. This creates multiple components, so it's invalid.
Example 2 — Multiple Roots
$
Input:
leftChild = [1,0,3,-1], rightChild = [-1,-1,-1,-1]
›
Output:
false
💡 Note:
Nodes 0 and 1 point to each other as children, creating a cycle. Also node 2 has no parent, creating multiple components.
Example 3 — Simple Valid Tree
$
Input:
leftChild = [1,2,-1,-1], rightChild = [-1,-1,-1,-1]
›
Output:
true
💡 Note:
Node 0 is root with left child 1. Node 1 has left child 2. Forms valid tree: 0->1->2
Constraints
- n == leftChild.length == rightChild.length
- 1 ≤ n ≤ 104
- -1 ≤ leftChild[i], rightChild[i] ≤ n - 1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code