Python 0558.py
class Solution:
def intersect(self, quadTree1: 'Node', quadTree2: 'Node') -> 'Node':
# process leaf: if it's True then the whole subtree is True
if quadTree1.isLeaf:
if quadTree1.val is True:
return Node(True, True)
else:
return quadTree2
# same as above, but the other way round
if quadTree2.isLeaf:
if quadTree2.val is True:
return Node(True, True)
else:
return quadTree1
# now we have an inner node, let's convert it's subnodes
sub = []
sub.append(self.intersect(quadTree1.topLeft, quadTree2.topLeft))
sub.append(self.intersect(quadTree1.topRight, quadTree2.topRight))
sub.append(self.intersect(quadTree1.bottomLeft, quadTree2.bottomLeft))
sub.append(self.intersect(quadTree1.bottomRight, quadTree2.bottomRight))
# it's possible that all subtrees have the same value => convert to a leaf
if all([ s.isLeaf for s in sub ]):
if all([ s.val == sub[0].val for s in sub ]):
return Node(sub[0].val, True)
# recursion for the win
return Node(False, False, sub[0], sub[1], sub[2], sub[3])
Difficulty
and has an acceptance rate of about 53% (30k+ submissions).
Typical patterns to solve this problem:
- Divide And Conquer
- Tree
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 intersect method merges two quad-tree representations of boolean grids, producing a new quad-tree that reflects the logical OR of the input regions. The algorithm proceeds by examining the leaf status of each node, handling trivial cases early, and then recursing on the four quadrants when both inputs are internal nodes. After the recursive calls, it checks whether the four resulting children can be collapsed into a single leaf, thereby keeping the tree as compact as possible.
Leaf handling for the first tree
if quadTree1.isLeaf:
if quadTree1.val is True:
return Node(True, True)
else:
return quadTree2
When the first argument is a leaf, the code distinguishes two possibilities. If the leaf represents a region that is entirely True, the result of the OR operation is also entirely True, so a new leaf node with value True is returned immediately. If the leaf is False, the result depends solely on the second tree, and the method returns quadTree2 unchanged.
Symmetric leaf handling for the second tree
if quadTree2.isLeaf:
if quadTree2.val is True:
return Node(True, True)
else:
return quadTree1
The same logic is applied when the second argument is a leaf. This symmetry ensures that the function treats both inputs uniformly and avoids redundant recursion when one side already determines the outcome.
Recursive combination of quadrants
sub = []
sub.append(self.intersect(quadTree1.topLeft, quadTree2.topLeft))
sub.append(self.intersect(quadTree1.topRight, quadTree2.topRight))
sub.append(self.intersect(quadTree1.bottomLeft, quadTree2.bottomLeft))
sub.append(self.intersect(quadTree1.bottomRight, quadTree2.bottomRight))
If neither input is a leaf, the method recurses on each corresponding pair of child quadrants: top-left, top-right, bottom-left, and bottom-right. The results are collected in the list sub. This step builds the combined tree depth-first, preserving the spatial relationship of each quadrant.
Leaf consolidation after recursion
if all([ s.isLeaf for s in sub ]):
if all([ s.val == sub[0].val for s in sub ]):
return Node(sub[0].val, True)
After the four recursive calls, the algorithm checks whether all four children are leaves and whether they share the same boolean value. If both conditions hold, the four homogeneous leaves are merged into a single leaf node, reducing the tree depth and eliminating unnecessary internal nodes. This consolidation step is crucial for maintaining the minimal representation of the quad-tree.
Construction of an internal node
return Node(False, False, sub[0], sub[1], sub[2], sub[3])
When the children cannot be collapsed, the method creates a new internal node whose isLeaf flag is False. The four previously computed subtrees become the children of this node, preserving the hierarchical structure required for further operations.
Edge case handling
The code explicitly handles the situation where one of the input trees is a leaf representing True. In that case, the result is a leaf with value True regardless of the structure of the other tree, because the logical OR of any region with True yields True. Conversely, when a leaf represents False, the algorithm defers to the other tree, effectively treating False as the identity element for the OR operation. This behavior correctly covers cases where one tree is entirely empty (all False) or entirely filled (all True).
Another subtle edge case is the possibility that after recursion all four children become identical leaves. The consolidation logic captures this scenario and replaces the four nodes with a single leaf, preventing the creation of redundant internal nodes that would otherwise increase the tree size without adding information.
Performance considerations
The early-exit checks for leaf nodes avoid unnecessary recursion when the outcome can be determined immediately, which reduces the number of function calls and the depth of the call stack. By returning the untouched subtree when a leaf is False, the algorithm reuses existing node objects instead of constructing new ones, saving both time and memory.
The consolidation step after the recursive calls serves as a form of bottom-up compression. By merging homogeneous leaves, the algorithm prevents the proliferation of internal nodes that would later need to be examined in subsequent operations. This compression not only keeps the resulting tree compact but also improves the efficiency of any later traversals, because fewer nodes need to be visited.
Collectively, these design choices ensure that the method operates efficiently on both sparse and dense quad-trees, scaling gracefully with the depth of the input structures while maintaining a minimal representation of the combined region.
ELI5 - Simplified Explanation
Imagine you have two big pictures made of smaller squares. Some squares are all colored in, and some are empty. You want to combine these two pictures into one new picture. To do this, you look at both pictures at the same time and decide what the new picture should look like.
First, check if one of the pictures is already just one solid color. If a piece of the first picture is all filled in, then the final result for that spot should be filled in too. If that piece is completely empty, you just take whatever is in the other picture for that same spot. It works exactly the same way if the second picture is the one that is all one color.
If both pictures have more details inside them, you split each one into four smaller corners. You look at the top left corner of the first picture and the top left corner of the second picture and combine them. You do this for the top right, bottom left, and bottom right corners too. Doing this creates four brand new pieces that will make up your new picture.
After putting those four pieces together, there is one last special trick. If all four of those new pieces turn out to be exactly the same, you can simplify everything. Instead of keeping them as four small boxes, you can turn them into one big, single piece of that same color. If they are all different, you just keep them together as they are, like a set of four tiles.
Code Quality
Complexity Analysis
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 | Go | Java | ||||
| LeetcodeHelp | C++ | Python | Java | |||||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| everthis | JS | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| lzl124631x | C++ | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Java | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| LeetcodeHelp | C++, Java, Python | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| everthis | JavaScript | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| lzl124631x | C++ | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 592: Fraction Addition and Subtraction
- problem 301: Remove Invalid Parentheses
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