Python 1361.py
class Solution:
def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
# single node
if n == 1:
return leftChild == [ -1 ] and rightChild == [ -1 ]
seen = set()
def check(i):
if i == -1: # terminal node
return True
if i >= n: # referencing an invalid node
return False
if i in seen: # don't visit a node twice
return False
seen.add(i)
return check(leftChild[i]) and check(rightChild[i])
# find root node
children = set()
for i in range(n):
if leftChild[i] != -1:
children.add(leftChild[i])
if rightChild[i] != -1:
children.add(rightChild[i])
root = -1
for i in set(range(n)) - children:
if leftChild[i] != -1 or rightChild[i] != -1:
if root != -1 and root != i:
return False # secondary root
root = i
if root == -1:
return False # no root node at all
# all nodes should be visited
return check(root) and len(seen) == n
Difficulty
and has an acceptance rate of about 44% (300k+ submissions).
Typical patterns to solve this problem:
- Binary Tree
- Breadth First Search
- Depth First Search
- Graph Theory
- Tree
- Union Find
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation determines whether a collection of node relationships describes a valid binary tree. It receives the total node count n and two parallel arrays, leftChild and rightChild, where each entry either holds the index of a child node or -1 to indicate the absence of a child. The algorithm validates structural constraints such as a single root, absence of cycles, and proper indexing, ultimately returning a Boolean result.
Handling the Trivial Single-Node Case
The function begins by treating the scenario where the tree consists of exactly one node. In this situation the only permissible configuration is that both child entries are -1. The code checks this directly:
if n == 1:
return leftChild == [-1] and rightChild == [-1]
By short-circuiting early, the routine avoids unnecessary work for the simplest input.
Detecting Invalid Indices and Cycles
A nested helper check performs a depth-first traversal while enforcing two critical constraints:
- An index equal to
-1signals a leaf and is accepted. - An index outside the range
[0, n-1]is rejected as an invalid reference.
The helper also maintains a seen set to guarantee that each node is visited at most once, thereby preventing cycles and duplicate parentage:
def check(i):
if i == -1:
return True
if i >= n:
return False
if i in seen:
return False
seen.add(i)
return check(leftChild[i]) and check(rightChild[i])
The early returns for terminal and out-of-bounds nodes allow the recursion to terminate promptly without exploring irrelevant branches.
Identifying the Root Node
A valid binary tree must contain exactly one node that is never referenced as a child. The algorithm constructs a set of all child indices and then determines which node(s) are absent from this set:
children = set()
for i in range(n):
if leftChild[i] != -1:
children.add(leftChild[i])
if rightChild[i] != -1:
children.add(rightChild[i])
After populating children, the code iterates over the complement of this set to locate the root. It also ensures that the candidate root is not an isolated node (i.e., it must have at least one child) and that there is at most one such root:
root = -1
for i in set(range(n)) - children:
if leftChild[i] != -1 or rightChild[i] != -1:
if root != -1 and root != i:
return False
root = i
if root == -1:
return False
This logic captures edge cases where multiple roots exist, where no root exists, or where the only non-child node is a leaf without children.
Verifying Full Connectivity
Having identified a unique root, the algorithm invokes the recursive check function starting from that root. It also confirms that the traversal visited every node by comparing the size of the seen set to n:
return check(root) and len(seen) == n
If any node remains unvisited, the structure would represent a forest rather than a single tree, causing the function to return False.
Edge Cases Addressed
- Single node without children - handled by the early
n == 1branch. - Child index equal to
-1- interpreted as a null pointer and accepted. - Child index out of bounds - detected by
i >= nand rejected. - Duplicate child references - caught by the
i in seentest, preventing cycles. - Multiple potential roots - the root-selection loop returns
Falsewhen more than one candidate satisfies the root criteria. - Absence of any root - the final
if root == -1guard captures this situation. - Disconnected components - the final size check ensures every node participates in the traversal.
Performance Optimizations
The implementation employs several techniques that keep the execution efficient:
- Early exit for trivial input - the single-node shortcut avoids unnecessary loops.
- Set-based membership checks - both
childrenandseenare hash-based, providing constant-time lookups for duplicate detection and root identification. - Single pass for child collection - the loop that builds
childrenprocesses each node exactly once. - Short-circuit logical operators - the recursive
checkreturnsFalseas soon as an invalid condition is encountered, preventing deeper unnecessary recursion. - Minimal auxiliary structures - only two sets are allocated, and the recursion reuses the same
seenset, limiting memory overhead.
Overall, the algorithm traverses the node list a constant number of times and performs depth-first recursion only along valid branches, delivering a solution that scales well with the size of the input.
ELI5 - Simplified Explanation
Imagine you are looking at a big family tree made of blocks. Every block can have a left side and a right side that connect to other blocks. This code acts like a detective to figure out if all the blocks are connected the right way to form one single, happy tree.
First, the detective looks for the very top block that has nothing holding it up. This is the root of the tree. If the detective finds two blocks trying to be the top, or finds no top block at all, it knows something is wrong.
After finding the right starting point, the detective goes on a walk through the tree. Every time it enters a new block, it puts a sticky note on it so it remembers it was there. Because a proper tree should not have any loops, the detective will stop if it ever sees a block that already has a sticky note on it.
Finally, the detective counts all the sticky notes. If it used the right amount of sticky notes to mark every single block exactly once, then it knows the tree is put together perfectly.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||
|---|---|---|---|---|---|---|---|
| author | solutions | ||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||
| WalkCCC | C++ | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | |||
| Progiez | C++ | Python | Java | ||||
| github | black-shadows | C++ | |||||
| charles-wangkai | Java | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JS | ||||||
| keineahnung2345 | C++ | ||||||
| lkwq007 | Python | ||||||
| YuriSpiridonov | Python | ||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||
| WalkCCC | C++, Java | ||||||
| leetcode.ca | C++, Go, Java, Python | ||||||
| Progiez | C++, Java, Python | ||||||
| black-shadows | C++, C++ | ||||||
| charles-wangkai | Java | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JavaScript | ||||||
| keineahnung2345 | C++ | ||||||
| lkwq007 | Python | ||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1603: Design Parking System
- problem 1656: Design an Ordered Stream
- problem 665: Non-decreasing Array
- problem 1472: Design Browser History
- problem 2166: Design Bitset
- problem 2502: Design Memory Allocator
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality