Validate Binary Tree Nodes — LeetCode 1361 Python Solution
- Problem
- #1361
- Pattern
- Union-Find
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- Input
- n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]
- Output
- true
Python solution
class Solution:
def validateBinaryTreeNodes(
self, n: int, leftChild: List[int], rightChild: List[int]
) -> bool:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
p = list(range(n))
vis = [False] * n
for i, (a, b) in enumerate(zip(leftChild, rightChild)):
for j in (a, b):
if j != -1:
if vis[j] or find(i) == find(j):
return False
p[find(i)] = find(j)
vis[j] = True
n -= 1
return n == 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \alpha(n)) |
| Space | O(n) auxiliary |
Pattern: Union-Find
Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 1361. Validate Binary Tree Nodes is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.
The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1361. Validate Binary Tree Nodes?
- LeetCode 1361. Validate Binary Tree Nodes is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1361. Validate Binary Tree Nodes?
- The Python solution on this page runs in O(n \times \alpha(n)).
- What is the space complexity of LeetCode 1361. Validate Binary Tree Nodes?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1361. Validate Binary Tree Nodes cover?
- LeetCode 1361. Validate Binary Tree Nodes is tagged Tree, Depth-First Search, Breadth-First Search, Union Find, Graph and Binary Tree on LeetCode.