# Question

Formatted question description: https://leetcode.ca/all/117.html

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.

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.


Example 2:

Input: root = []
Output: []


Constraints:

• The number of nodes in the tree is in the range [0, 6000].
• -100 <= Node.val <= 100

Follow-up:

• You may only use constant extra space.
• The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.

# Algorithm

### BFS

Since the subtree may be incomplete, it is necessary to scan the nodes in the same layer of the parent node in parallel to find their left and right child nodes.

### DFS

Same as in 116 - Populating Next Right Pointers in Each Node.

# Code

• public class Populating_Next_Right_Pointers_in_Each_Node_II {

public static void main(String[] args) {
Populating_Next_Right_Pointers_in_Each_Node_II out = new Populating_Next_Right_Pointers_in_Each_Node_II();

Solution_fancy s = out.new Solution_fancy();

s.connect(root);
}

/**
* Definition for binary tree with next pointer.
* int val;
* TreeLinkNode(int x) { val = x; }
* }
*/

public class Solution {

if (root == null) {
return;
}

q.offer(root);
q.offer(levelEndMarker);

while (!q.isEmpty()) {

if (current == levelEndMarker) {
// push marker again as next level end
if (!q.isEmpty()) { // @note: missed final check again...
q.offer(levelEndMarker);
}

// first node of each level, can not be last of upper level
prev = levelEndMarker; // can be any node which is not in this tree
continue;
}

if (current.left != null) {
q.offer(current.left);
}
if (current.right != null) {
q.offer(current.right);
}

prev.next = current;
prev = current;
}
}
}

class Solution_fancy {
TreeLinkNode pre = dummyHead; // this 'pre' will be the "current node" that builds every single layer
TreeLinkNode real_root = root; // just for return statement

while (root != null) {
if (root.left != null) {
pre.next = root.left; // @note: here pre is same as dummyHead, pointing to 1st node of this level. this is before pre is updated to be other nodes
pre = pre.next;
}
if (root.right != null) {
pre.next = root.right;
pre = pre.next;
}
root = root.next;
if (root == null) { // reach the end of current layer
pre = dummyHead; // shift pre back to the beginning, get ready to point to the first element in next layer
;//root comes down one level below to the first available non null node
dummyHead.next = null;//reset dummyhead back to default null, so that later it will point to next level's first node
}
}
return real_root;
}
}

}

############

/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;

public Node() {}

public Node(int _val) {
val = _val;
}

public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/

class Solution {
private Node prev, next;

public Node connect(Node root) {
Node node = root;
while (node != null) {
prev = null;
next = null;
while (node != null) {
modify(node.left);
modify(node.right);
node = node.next;
}
node = next;
}
return root;
}

private void modify(Node curr) {
if (curr == null) {
return;
}
if (next == null) {
next = curr;
}
if (prev != null) {
prev.next = curr;
}
prev = curr;
}
}

• // OJ: https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
// Time: O(N)
// Space: O(H)
class Solution {
public:
Node* connect(Node* root) {
if (!root) return nullptr;
for (auto node = root; node; node = node->next) {
if (node->left) {
tail->next = node->left;
tail = tail->next;
}
if (node->right) {
tail->next = node->right;
tail = tail->next;
}
}
return root;
}
};

• """
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: "Node") -> "Node":
def modify(curr):
nonlocal prev_node, next_node
if curr is None:
return
if next_node is None: # next level's first node
next_node = curr
# "if next_node is None" logic can be replaced by:
#   next_node = next_node or curr
if prev_node:
prev_node.next = curr
prev_node = curr

node = root
while node:
prev_node = next_node = None
while node: # process for every level
modify(node.left)
modify(node.right)
node = node.next
node = next_node
return root

# use dummyHead.next to find each level's first node
class Solution:
def connect(self, root: 'Node') -> 'Node':
real_root = root

while root:
if root.left:
# @note: here pre is same as dummyHead, pointing to 1st node of this level. this is before pre is updated to be other nodes
pre.next = root.left
pre = pre.next
if root.right:
pre.next = root.right
pre = pre.next
root = root.next
if not root: # reach the end of current layer
pre = dummyHead # shift pre back to the beginning, get ready to point to the first element in next layer
root = dummyHead.next # root comes down one level below to the first available non null node
dummyHead.next = None # reset dummyhead back to default null, so that later it will point to next level's first node

return real_root

###############

# Definition for binary tree with next pointer.
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.next = None

class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
p = root
pre = None
while p:
if p.left:
if pre:
pre.next = p.left
pre = p.left
if p.right:
if pre:
pre.next = p.right
pre = p.right
if p.next:
p = p.next
else:
pre = None


• /**
* Definition for a Node.
* type Node struct {
*     Val int
*     Left *Node
*     Right *Node
*     Next *Node
* }
*/

func connect(root *Node) *Node {
node := root
var prev, next *Node
modify := func(curr *Node) {
if curr == nil {
return
}
if next == nil {
next = curr
}
if prev != nil {
prev.Next = curr
}
prev = curr
}
for node != nil {
prev, next = nil, nil
for node != nil {
modify(node.Left)
modify(node.Right)
node = node.Next
}
node = next
}
return root
}

• /**
* Definition for Node.
* class Node {
*     val: number
*     left: Node | null
*     right: Node | null
*     next: Node | null
*     constructor(val?: number, left?: Node, right?: Node, next?: Node) {
*         this.val = (val===undefined ? 0 : val)
*         this.left = (left===undefined ? null : left)
*         this.right = (right===undefined ? null : right)
*         this.next = (next===undefined ? null : next)
*     }
* }
*/

function connect(root: Node | null): Node | null {
if (root == null) {
return root;
}
const queue = [root];
while (queue.length !== 0) {
const n = queue.length;
let pre = null;
for (let i = 0; i < n; i++) {
const node = queue.shift();
node.next = pre;
pre = node;
const { left, right } = node;
right && queue.push(right);
left && queue.push(left);
}
}
return root;
}