#1361
Validate Binary Tree Nodes
MediumTreeDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryBinary TreeGraph TheoryTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a single pass to track parent-child relationships and ensures that there is exactly one root node and that no node has more than one parent. This is efficient and avoids unnecessary checks.
⚙️
Algorithm
4 steps- 1Step 1: Create an array to track the number of parents for each node.
- 2Step 2: Iterate through each node and for each child (left and right), increment the parent's count.
- 3Step 3: Count the number of nodes with zero parents (potential roots).
- 4Step 4: Check that there is exactly one root and that no node has more than one parent.
solution.py11 lines
1# Full working Python code
2
3def validateBinaryTreeNodes(n, leftChild, rightChild):
4 parent_count = [0] * n
5 for i in range(n):
6 if leftChild[i] != -1:
7 parent_count[leftChild[i]] += 1
8 if rightChild[i] != -1:
9 parent_count[rightChild[i]] += 1
10 root_count = sum(1 for count in parent_count if count == 0)
11 return root_count == 1 and all(count <= 1 for count in parent_count)ℹ
Complexity note: The time complexity is O(n) as we make a single pass through the nodes to count parents, and the space complexity is O(n) due to the parent count array.
- 1A valid binary tree must have exactly one root node.
- 2Each node can have at most one parent; no cycles are allowed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.