Created
August 20, 2015 09:14
-
-
Save xynophon/858cddb8b88ac4b60f19 to your computer and use it in GitHub Desktop.
LeetCode Populating Next Right Pointers in Each Node II
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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