Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Next Right Pointer
package com.interviewbytes.trees;
import java.util.Deque;
import java.util.LinkedList;
public class NextRightPointer {
public void connect(TreeLinkNode root) {
if (root == null) return;
Deque<TreeLinkNode> deque = new LinkedList<>();
if (root.left != null) deque.offer(root.left);
if (root.right != null) deque.offer(root.right);
while (!deque.isEmpty()) {
int size = deque.size();
TreeLinkNode next = null;
while (size > 0) {
TreeLinkNode node = deque.pollLast();
if (node.left != null) deque.offerFirst(node.right);
if (node.right != null) deque.offerFirst(node.left);
node.next = next;
next = node;
size--;
}
}
}
}
package com.interviewbytes.trees;
public class TreeLinkNode {
int val;
TreeLinkNode left, right, next;
TreeLinkNode(int x) {
val = x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.