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:
true
💡 Note:
Node 0 is root, has left child 1. Node 1 has right child 2. Node 2 has left child 0 (cycle). Actually this forms: 0->1, 1->2, 2->0, which is a cycle, so should be false. Let me correct: Node 0 has left=1, Node 1 has right=2, Node 2 has left=0. This creates a cycle.
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
Understanding the Visualization
1
Input Arrays
leftChild and rightChild arrays define parent-child relationships
2
Validation
Check for single root, no multiple parents, and connectivity
3
Result
Return true if forms valid binary tree, false otherwise
Key Takeaway
🎯 Key Insight: A valid binary tree has exactly one root and forms a connected acyclic structure
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code