Leetcode #558: Logical OR of Two Binary Grids Represented as Quad-Trees
In this guide, we solve Leetcode #558 Logical OR of Two Binary Grids Represented as Quad-Trees in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
A Binary Matrix is a matrix in which all the elements are either 0 or 1. Given quadTree1 and quadTree2.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Tree, Divide and Conquer
Intuition
The input is a tree, so recursive decomposition is a natural fit.
We can compute the answer by combining results from left and right subtrees.
Approach
Use DFS and pass the required state through recursive calls.
Combine child results to compute the answer for each node.
Steps:
- Pick traversal order.
- Recurse with state.
- Combine results from children.
Example
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
}
Python Solution
"""
# Definition for a QuadTree node.
class Node:
def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
self.val = val
self.isLeaf = isLeaf
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = bottomRight
"""
class Solution:
def intersect(self, quadTree1: "Node", quadTree2: "Node") -> "Node":
def dfs(t1, t2):
if t1.isLeaf and t2.isLeaf:
return Node(t1.val or t2.val, True)
if t1.isLeaf:
return t1 if t1.val else t2
if t2.isLeaf:
return t2 if t2.val else t1
res = Node()
res.topLeft = dfs(t1.topLeft, t2.topLeft)
res.topRight = dfs(t1.topRight, t2.topRight)
res.bottomLeft = dfs(t1.bottomLeft, t2.bottomLeft)
res.bottomRight = dfs(t1.bottomRight, t2.bottomRight)
isLeaf = (
res.topLeft.isLeaf
and res.topRight.isLeaf
and res.bottomLeft.isLeaf
and res.bottomRight.isLeaf
)
sameVal = (
res.topLeft.val
== res.topRight.val
== res.bottomLeft.val
== res.bottomRight.val
)
if isLeaf and sameVal:
res = res.topLeft
return res
return dfs(quadTree1, quadTree2)
Complexity
The time complexity is O(n). The space complexity is O(h).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.