Problem 117

Abstract / Summary

Given a binary tree connect each node to its next right node even if the tree is not perfect using only constant extra space.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
18 lines | 465 bytes | submitted August 31, 2023 | GitHub   7% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.04 | σ = 1.29

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
51 links | 35 authors | 9 languages

Videos

13 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

27 solutions   August 31, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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