MediumNo. 1361

Validate Binary Tree Nodes — LeetCode 1361 Python Solution

Pattern
Union-Find
Topics
Tree, Depth-First Search, Breadth-First Search, Union Find, Graph, Binary Tree
Reading time
4 min

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

PythonSolution
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 == 1

Complexity

Time
O(n × α(n))
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0399Evaluate DivisionMedium
0547Number of ProvincesMedium
0684Redundant ConnectionMedium
0685Redundant Connection IIHard
0785Is Graph Bipartite?Medium
0886Possible BipartitionMedium

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 × α(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.