Logical OR of Two Binary Grids Represented as Quad-Trees - Problem

A Binary Matrix is a matrix in which all the elements are either 0 or 1.

Given quadTree1 and quadTree2. quadTree1 represents a n * n binary matrix and quadTree2 represents another n * n binary matrix.

Return a Quad-Tree representing the n * n binary matrix which is the result of logical bitwise OR of the two binary matrices represented by quadTree1 and quadTree2.

A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:

  • val: True if the node represents a grid of 1's or False if the node represents a grid of 0's.
  • isLeaf: True if the node is leaf node on the tree or False if the node has the four children.

Quad-Tree Construction Rules:

  • If the current grid has the same value (all 1's or all 0's), set isLeaf to True and set val to the value of the grid.
  • If the current grid has different values, set isLeaf to False and divide the current grid into four sub-grids: topLeft, topRight, bottomLeft, bottomRight.

Input & Output

Example 1 — Basic OR Operation
$ Input: quadTree1 = [[0,1],[1,1],[1,1],[1,0],[1,1]], quadTree2 = [[0,1],[1,1],[0,1],[1,1],[1,0]]
Output: [[0,1],[1,1],[1,1],[1,1],[1,1]]
💡 Note: First tree represents [[0,1],[1,1]], second tree represents [[1,1],[1,0]]. OR operation results in [[1,1],[1,1]] which becomes a single leaf node with value 1.
Example 2 — Single Cell Trees
$ Input: quadTree1 = [[1,0]], quadTree2 = [[1,1]]
Output: [[1,1]]
💡 Note: Both trees represent single cells: 0 OR 1 = 1. Result is a single leaf with value 1.
Example 3 — No Simplification Possible
$ Input: quadTree1 = [[0,1],[1,0],[1,1],[1,1],[1,0]], quadTree2 = [[0,1],[1,1],[0,1],[1,0],[1,1]]
Output: [[0,1],[1,1],[0,1],[1,1],[1,1]]
💡 Note: Trees represent different patterns that when OR'ed together create a mixed result that cannot be simplified to a single leaf.

Constraints

  • quadTree1 and quadTree2 are both valid Quad-Trees
  • n == 2x where 0 ≤ x ≤ 9
  • Both trees represent the same size grid

Visualization

Tap to expand
Quad-Tree OR Operation OverviewQuad-Tree 10111Quad-Tree 21110Logical ORResult Tree1111Matrix: [[0,1],[1,1]] OR [[1,1],[1,0]] = [[1,1],[1,1]]Result: Single leaf node with val=true (all 1s)
Understanding the Visualization
1
Input Trees
Two quad-trees representing binary matrices
2
OR Operation
Combine corresponding regions using logical OR
3
Result Tree
New quad-tree representing the OR'ed matrix
Key Takeaway
🎯 Key Insight: OR operation allows early termination when any region contains all 1's, making direct tree combination more efficient than matrix conversion
Asked in
Google 15 Facebook 12 Amazon 8
28.5K Views
Medium Frequency
~25 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen