Python 0116.py
class Solution:
stacks = { }
def inorder(self, root, depth = 0):
if not root:
return None
prev = self.stacks.get(depth)
if prev:
prev.next = root
self.stacks[depth] = root
self.inorder(root.left, depth + 1)
self.inorder(root.right, depth + 1)
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
self.inorder(root)
return root
Difficulty
and has an acceptance rate of about 68% (2+ million submissions).
Typical patterns to solve this problem:
- Binary Tree
- Breadth First Search
- Depth First Search
- Linked List
- 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 provided module defines a Solution class that populates the next pointers of a binary tree so that each node points to its immediate neighbor on the same depth level. The algorithm performs a depth-first traversal, records the most recent node encountered at each depth, and links the current node to that recorded predecessor. The public entry point is the connect method, which initiates the traversal and returns the modified tree root.
Core Components
Class-level storage
class Solution:
stacks = { }
A dictionary named stacks lives on the class object, acting as a map from depth values to the latest node visited at that depth. Because it is shared across all instances, the structure persists for the duration of a single connect call, eliminating the need to allocate a new container for each recursion level.
Recursive depth-first routine
def inorder(self, root, depth = 0):
if not root:
return None
prev = self.stacks.get(depth)
if prev:
prev.next = root
self.stacks[depth] = root
self.inorder(root.left, depth + 1)
self.inorder(root.right, depth + 1)
The method receives a node and its depth. The first guard clause returns immediately when the node is None, handling the case of an empty subtree without further processing.
The line prev = self.stacks.get(depth) retrieves the previously visited node at the same depth, if any. When such a predecessor exists, its next attribute is set to the current node, establishing the horizontal link. The dictionary entry for the current depth is then updated to reference the current node, ensuring that subsequent nodes on the same level will be linked to it.
The recursion proceeds first to the left child, then to the right child, both with an incremented depth value. This order guarantees that nodes are visited from left to right within each level, which is essential for correctly ordering the next pointers.
Public interface
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
self.inorder(root)
return root
The connect method serves as the API entry point. It triggers the depth-first traversal starting at depth zero and finally returns the original root, now enriched with the next connections.
Edge-Case Handling
When the input tree is completely empty, the initial call to inorder receives root as None. The guard clause if not root: return None terminates the recursion instantly, leaving the stacks dictionary untouched and returning None from connect.
If a node lacks a left or right child, the recursive call for that missing child receives None. Again, the guard clause prevents any further action, ensuring that the algorithm does not attempt to access attributes of a non-existent node.
The use of self.stacks.get(depth) safely returns None when no predecessor exists at a particular depth, such as the first node encountered on a new level. The subsequent conditional if prev: prevents an attempt to assign to prev.next when prev is None, thereby avoiding attribute errors.
Performance Optimizations
The algorithm leverages a single dictionary to keep track of the most recent node per depth, eliminating the need for auxiliary queues or lists that are common in breadth-first approaches. By updating the dictionary in place, the code avoids repeated allocations and reduces memory churn.
Because the traversal visits each node exactly once and performs only constant-time dictionary operations per node, the overall work scales linearly with the number of nodes. The recursion depth mirrors the height of the tree, and the dictionary size grows only with the maximum depth, keeping auxiliary storage proportional to the tree’s breadth rather than its total size.
Storing the next pointer directly on the existing node objects avoids creating new wrapper structures, which contributes to lower memory overhead and better cache locality during the traversal.
The left-to-right visitation order within each depth level ensures that the next pointers are assigned in the correct sequence without requiring a second pass or additional sorting logic. This in-place linking strategy streamlines the process and reduces the total number of operations.
ELI5 - Simplified Explanation
Imagine a big family tree made of blocks where each block has a spot for a left sub-block and a right sub-block. The goal here is to link all the blocks that sit on the same level of the tree. There is a special helper called stacks that keeps track of the very last block seen at every depth level as the code travels down the tree.
When the instructions reach a new block, they check that list to see if another block was already visited at that same depth level. If one was found, the code connects the old block to the new one by setting a special pointer. After that, the code saves the current block as the champion for that level. Then, it carefully repeats these steps for all the blocks to the left and all the blocks to the right. By going through every single piece of the tree this way, every block ends up pointing to its neighbor on the same floor.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
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++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | begeekmyfriend | C | ||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | Python | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| Dijkstra-Edu | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| FelixFan1122 | C# | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| Garvit244 | Python | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| lennylxx | C | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| luangong | C++ | |||||||||
| MacJim | C++ | |||||||||
| qiyuangong | Python | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| vthwang | Java | |||||||||
| XiaotaoGuo | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| begeekmyfriend | C | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | Python, Python | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| Dijkstra-Edu | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| FelixFan1122 | C# | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| Garvit244 | Python | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| lennylxx | C | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| luangong | C++ | |||||||||
| MacJim | C++ | |||||||||
| qiyuangong | Python | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| vthwang | Java | |||||||||
| XiaotaoGuo | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 117: Populating Next Right Pointers in Each Node II
- problem 199: Binary Tree Right Side View
Solved On The Same Day
- problem 112: Path Sum
- problem 409: Longest Palindrome
- problem 645: Set Mismatch
- problem 717: 1-bit and 2-bit Characters
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 16: 3Sum Closest
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 114: Flatten Binary Tree to Linked List
- problem 129: Sum Root to Leaf Numbers
- problem 131: Palindrome Partitioning
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 165: Compare Version Numbers
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 539: Minimum Time Difference
- problem 583: Delete Operation for Two Strings
- problem 633: Sum of Square Numbers
- problem 648: Replace Words
- problem 650: 2 Keys Keyboard
- problem 670: Maximum Swap
- problem 786: K-th Smallest Prime Fraction
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
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