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
Validate Binary Tree Nodes INPUT n = 4 nodes (0 to 3) 0 1 2 3 leftChild Array: 1 -1 0 -1 [0] [1] [2] [3] rightChild Array: -1 2 -1 -1 [0] [1] [2] [3] ALGORITHM STEPS 1 Count Parent Refs Track how many parents each node has 2 Find Root Root has 0 parents Must be exactly one 3 Validate Parents Each non-root node has exactly 1 parent 4 Check Connectivity BFS/DFS from root reaches all n nodes Parent Count: 0 1 1 1 node0 node1 node2 node3 Root = Node 0 (0 parents) FINAL RESULT Valid Binary Tree Structure: 0 ROOT 1 2 3 left right left Output: true [OK] Valid single tree Key Insight: A valid binary tree has exactly ONE root (0 parents), every other node has exactly ONE parent, and all nodes are connected. Single pass: count parents, find root, verify connectivity with BFS/DFS. Time: O(n) | Space: O(n) for parent count array and visited set TutorialsPoint - Validate Binary Tree Nodes | Single Pass Validation
Asked in
Google 15 Facebook 12 Amazon 8
35.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen