Python 0117.py
class Solution:
def connect(self, root: 'Node') -> 'Node':
rightmost = { }
def deeper(node, depth):
if not node:
return
if depth in rightmost:
node.next = rightmost[depth]
rightmost[depth] = node
# order is important !
deeper(node.right, depth+1)
deeper(node.left, depth+1)
deeper(root, 0)
return root
Difficulty
and has an acceptance rate of about 58% (1+ 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 implementation defines a Solution class with a connect method that populates each node’s next pointer to refer to the node immediately to its right on the same depth level. The algorithm walks the tree recursively, maintaining a mapping from depth to the most recently visited node at that depth. By traversing the right subtree before the left subtree, the method ensures that when a node is processed, the node stored in the mapping is precisely the one that should become its next.
Key Steps
The core of the solution resides in the nested deeper function. The first important step is the creation of the rightmost dictionary that will hold the latest node for each depth.
rightmost = {}
The deeper function is defined to accept a node and its current depth. The base case checks for a null node and returns immediately, preventing further recursion.
def deeper(node, depth):
if not node:
return
When a node is present, the function looks up whether a node has already been recorded for the current depth. If such a node exists, the current node’s next pointer is linked to that previously stored node.
if depth in rightmost:
node.next = rightmost[depth]
After establishing the link (or leaving next as None when no right neighbor exists), the dictionary entry for the current depth is updated to the current node, making it the new rightmost node for any subsequent nodes at the same depth.
rightmost[depth] = node
The traversal order is deliberately chosen: the right child is visited before the left child. This ordering guarantees that when the left child is processed, the dictionary already contains the node that lies directly to its right.
deeper(node.right, depth + 1)
deeper(node.left, depth + 1)
The recursion is initiated with the root node at depth zero, and the method finally returns the modified root.
deeper(root, 0)
return root
Edge Cases Handled
When the input tree is empty (root is None), the initial call to deeper receives a null node, triggers the base-case return, and the method returns None without performing any further work.
A tree consisting of a single node also passes through the same flow: the dictionary is empty at depth zero, so the node’s next remains None, and the dictionary is updated with that node. The recursion then terminates after the null children are encountered.
Unbalanced trees, where some branches are deeper than others, are accommodated because the depth key is created on demand. Each distinct depth receives its own entry, and the algorithm does not rely on any assumption of completeness or perfect balance.
Deep trees that could potentially cause a large recursion depth are still processed correctly; the recursion simply follows the natural call stack without additional data structures, and each call handles its own depth independently.
Performance Optimizations
The solution achieves its goal with a single pass over the tree. By using a dictionary (rightmost) that provides constant-time lookup and update for each depth, the algorithm avoids the need for auxiliary queues or lists that are common in breadth-first approaches.
The right-to-left traversal order eliminates the necessity of a second pass to reverse the direction of links. As each node is visited, the appropriate neighbor is already known, allowing the next pointer to be set immediately.
Because the recursion carries only the current node and its depth, the memory footprint is limited to the call stack depth plus the dictionary entries for each distinct depth, which is proportional to the height of the tree rather than the total number of nodes. This design keeps auxiliary memory usage minimal while still delivering the required linking behavior.
ELI5 - Simplified Explanation
Imagine you have a big family tree made of blocks. At the very top, there is one big block, and underneath it, more blocks spread out like branches. This code is like a little helper going down the branches to connect all the blocks that are sitting on the same level.
First, it makes a little notebook to remember which block is the rightmost one for every floor of the tree. It starts at the top floor, which is floor zero. It looks at the block, checks if it knows anyone else on that same floor from the notebook, and draws a line to them if it does. Then, it writes that block down in the notebook so the next one on that floor knows who to connect to.
Because the code wants to finish the right side first to make the connections easier, it visits the right branch of the tree before the left branch. It just keeps going deeper and deeper, floor by floor, until every block is holding hands with its neighbor on the same level. Once it gets to the bottom of a branch, it turns around and moves back up to find the next path to explore. After it has finished visiting every single block, everyone on the same level is officially connected.
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 | Python | C++ | Java | TS | |||||
| WalkCCC | Python | C++ | Java | |||||||
| leetcode.ca | Python | C++ | Java | C# | TS | Go | ||||
| LeetcodeHelp | Python | C++ | Java | |||||||
| MemoryLimitExceeded | Python | C++ | ||||||||
| Progiez | Python | C++ | Java | |||||||
| github | begeekmyfriend | C | ||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | Python | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| Dijkstra-Edu | Java | |||||||||
| DimitrisJim | Python | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| Garvit244 | Python | |||||||||
| haoel | Python | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| luangong | C++ | TS | ||||||||
| MacJim | C++ | |||||||||
| qiyuangong | Python | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, 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 | Python | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| Garvit244 | Python | |||||||||
| haoel | Python | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| luangong | C++, TypeScript | |||||||||
| MacJim | C++ | |||||||||
| qiyuangong | Python | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 116: Populating Next Right Pointers in Each Node
Solved On The Same Day
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 118: Pascal's Triangle
- problem 119: Pascal's Triangle II
- problem 228: Summary Ranges
- problem 530: Minimum Absolute Difference in BST
- problem 82: Remove Duplicates from Sorted List II
- problem 102: Binary Tree Level Order Traversal
- problem 103: Binary Tree Zigzag Level Order Traversal
- problem 105: Construct Binary Tree from Preorder and Inorder Traversal
- problem 106: Construct Binary Tree from Inorder and Postorder Traversal
- problem 107: Binary Tree Level Order Traversal II
- problem 109: Convert Sorted List to Binary Search Tree
- problem 128: Longest Consecutive Sequence
- problem 138: Copy List with Random Pointer
- problem 150: Evaluate Reverse Polish Notation
- problem 155: Min Stack
- problem 209: Minimum Size Subarray Sum
- problem 274: H-Index
- problem 380: Insert Delete GetRandom O(1)
- problem 427: Construct Quad Tree
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 30: Substring with Concatenation of All Words
- problem 37: Sudoku Solver
- problem 44: Wildcard Matching
- problem 1326: Minimum Number of Taps to Open to Water a Garden
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