Problem 116

Abstract / Summary

Connect each node in a binary tree to its next right node using existing next pointers.

Note

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

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
19 lines | 462 bytes | submitted August 15, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
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 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.

written by openai gpt

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.

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 = 4 | μ = 4.48 | σ = 1.79

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 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++
55 links | 41 authors | 9 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Populating Next Right Pointers in Each Node - Leetcode 116 - Python'
NeetCode 10 mins
Populating Next Right Pointers in Each Node - Leetcode 116 - Python
YouTube video 'Populating Next Right Pointers in Each Node || Leetcode'
Pepcoding 11 mins
Populating Next Right Pointers in Each Node || Leetcode
YouTube video 'Populating Next Right Pointers in Each Node🔥 | Leetcode 116| Binary Tree'
Ayushi Sharma 13 mins
Populating Next Right Pointers in Each Node🔥 | Leetcode 116| Binary Tree
YouTube video 'LeetCode 116 | Populating Next Right Pointers in Each Node'
Xavier Elon 7 mins
LeetCode 116 | Populating Next Right Pointers in Each Node
YouTube video 'Populating Next Right Pointers in Each Node | Live Coding with Explanation | Leetcode #116'
Algorithms Made Easy 4 mins
Populating Next Right Pointers in Each Node | Live Coding with Explanation | Leetcode #116
YouTube video 'Populating Next Right Pointers in Each Node | Leet code 116 | Theory explained + Python code'
Sai Anish Malla 15 mins
Populating Next Right Pointers in Each Node | Leet code 116 | Theory explained + Python code
YouTube video 'populating next right pointers in each node leetcode | leetcode 116 | bfs level order'
Naresh Gupta 13 mins
populating next right pointers in each node leetcode | leetcode 116 | bfs level order
YouTube video 'FACEBOOK Coding Interview Question - Populating Next Right Pointers in Each Node | LeetCode'
JeanTheCoder 14 mins
FACEBOOK Coding Interview Question - Populating Next Right Pointers in Each Node | LeetCode
YouTube video 'LeetCode 116. Populating Next Right Pointers in Each Node'
Happy Coding 17 mins
LeetCode 116. Populating Next Right Pointers in Each Node
YouTube video 'Daily Leetcode #227: Nov 13, 2020 - 116. Populating Next Right Pointers in Each Node'
Programming Live with Larry 14 mins
Daily Leetcode #227: Nov 13, 2020 - 116. Populating Next Right Pointers in Each Node
YouTube video 'Daily Leetcode #638: Dec 29, 2021 - 116. Populating Next Right Pointers in Each Node'
Programming Live with Larry 12 mins
Daily Leetcode #638: Dec 29, 2021 - 116. Populating Next Right Pointers in Each Node
YouTube video 'Day 231: LeetCode Problem 117. Populating Next Right Pointers in Each Node II - Swift'
iOSxBank 9 mins
Day 231: LeetCode Problem 117. Populating Next Right Pointers in Each Node II - Swift
YouTube video '117. Populating Next Right Pointers in Each Node II | Leetcode Unlocked - Python'
Leetcode Unlocked 7 mins
117. Populating Next Right Pointers in Each Node II | Leetcode Unlocked - Python
YouTube video 'LeetCode 116. Populating Next Right Pointers in Each Node'
Education, the study of everything 5 mins
LeetCode 116. Populating Next Right Pointers in Each Node
YouTube video '116. Populating Next Right Pointers in Each Node | Leetcode | Python'
Abdullah Arshed 5 mins
116. Populating Next Right Pointers in Each Node | Leetcode | Python
YouTube video 'LeetCode 116 | Populating Next Right Pointers in Each Node | BFS | Java'
Sleepy Cracker 4 mins
LeetCode 116 | Populating Next Right Pointers in Each Node | BFS | Java
YouTube video '27. LeetCode 116. Populating Next Right Pointers in Each Node [ JAVASCRIPT ]'
Web Fusion with Bharadwaj 4 mins
27. LeetCode 116. Populating Next Right Pointers in Each Node [ JAVASCRIPT ]
YouTube video 'LeetCode 116 | Populating Next Right Pointers in Each Node | Tree | Java'
Sleepy Cracker 3 mins
LeetCode 116 | Populating Next Right Pointers in Each Node | Tree | Java
YouTube video '116. Populating Next Right Pointers in Each Node (LeetCode)'
hakunamatasq 4 mins
116. Populating Next Right Pointers in Each Node (LeetCode)
19 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

30 solutions   August 15, 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