Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active August 29, 2017 20:54
Show Gist options
  • Save cixuuz/a7d6d46f0a14d1b8a0cf2132c2675a53 to your computer and use it in GitHub Desktop.
Save cixuuz/a7d6d46f0a14d1b8a0cf2132c2675a53 to your computer and use it in GitHub Desktop.
[117. Populating Next Right Pointers in Each Node II] #leetcode
public class Solution {
// O(n) O(n)
public void connect(TreeLinkNode root) {
if ( root == null ) return;
Deque<TreeLinkNode> deque = new LinkedList<TreeLinkNode>();
deque.addLast(root);
while ( !deque.isEmpty() ) {
int n = deque.size();
for ( int i = 0 ; i < n ; i++ ) {
TreeLinkNode node = deque.removeFirst();
if ( i != n - 1 ) {
node.next = deque.peekFirst();
}
if ( node.left != null ) deque.addLast(node.left);
if ( node.right != null ) deque.addLast(node.right);
}
}
}
}
public class Solution {
// O(n) O(1)
public void connect(TreeLinkNode root) {
while ( root != null ) {
TreeLinkNode leftmostChild = new TreeLinkNode(0);
TreeLinkNode currentChild = leftmostChild;
while ( root != null ) {
if ( root.left != null ) {
currentChild.next = root.left;
currentChild = currentChild.next;
}
if ( root.right != null ) {
currentChild.next = root.right;
currentChild = currentChild.next;
}
root = root.next;
}
root = leftmostChild.next;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment