117. Populating Next Right Pointers in Each Node II
LeetCode 117. Populating Next Right Pointers in Each Node II****
Description
Given a binary tree
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
Follow up:
You may only use constant extra space.
Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
Example 1:

Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Constraints:
The number of nodes in the given tree is less than
6000
.-100 <= node.val <= 100
Tags
Tree, Breadth-first Search
Solution
You can still use the solution in LeetCode 116. However, there is a O(1) space complexity solution.
We can connect nodes in the next level from the current level. We use a pointer last
to traverse and connect all nodes in the next level starting from the first node in the next level. Also, we initialize a pointer nextStart
to indicate the first node in the next level.
Traverse the current level, we process the left and right children (if exists) of each node. If last
is not null, we assign the current child node to its Next, and move last
to this child node. If nextStart
is null, we assign the first child node to it as the first node in the next level. After processing all nodes in the current level, we begin to process from nextStart
, only if it is not null.
Complexity
Time complexity:
Space complexity:
Code
func connect(root *Node) *Node {
start := root
for start != nil {
// the start node in next level, a pt to traverse the current level
var nextStart, last *Node
handle := func(cur *Node) {
if cur == nil {
return
}
if nextStart == nil {
nextStart = cur
}
if last != nil {
last.Next = cur
}
last = cur
}
for p := start; p != nil; p = p.Next {
handle(p.Left)
handle(p.Right)
}
start = nextStart
}
return root
}
Reference
Last updated
Was this helpful?