Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save xynophon/858cddb8b88ac4b60f19 to your computer and use it in GitHub Desktop.

Select an option

Save xynophon/858cddb8b88ac4b60f19 to your computer and use it in GitHub Desktop.
LeetCode Populating Next Right Pointers in Each Node II
import java.util.*;
public class PopulatingNextRightPointersinEachNodeII {
public class TreeLinkNode {
int val;
TreeLinkNode left, right, next;
TreeLinkNode(int x) { val = x; }
}
public void connect(TreeLinkNode root) {
Queue<TreeLinkNode> qu = new LinkedList<>();
if(root != null) {
qu.add(root);
while (!qu.isEmpty()) {
int n = qu.size();
for (int i = 0; i < n; i++) {
TreeLinkNode p = qu.remove();
if (p.left != null) qu.add(p.left);
if (p.right != null) qu.add(p.right);
if (i == n - 1) {
p.next = null;
} else {
p.next = qu.peek();
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment