# Populating Next Right Pointers in Each Node I II@LeetCode

## Populating Next Right Pointers in Each Node I

````java````public class Solution {
public void connect(TreeLinkNode root) {
if (root == null)
return;
LinkedList<TreeLinkNode> nodes = new LinkedList<TreeLinkNode>();
nodes.add(root);
int numOfLevelTotal = 1;
while (!nodes.isEmpty()) {
TreeLinkNode treeLinkNode = nodes.poll();
numOfLevelTotal--;
if (treeLinkNode.left != null) {
nodes.add(treeLinkNode.left);
}
if (treeLinkNode.right != null) {
nodes.add(treeLinkNode.right);
}
if (numOfLevelTotal > 0) {
treeLinkNode.next = nodes.getFirst();
} else {
numOfLevelTotal = nodes.size();
}
}
}
}
``````

## Populating Next Right Pointers in Each Node II

What if the given tree could be any binary tree? Would your previous solution still work?

You may only use constant extra space.

````java````public class Solution {
public void connect(TreeLinkNode root) {
TreeLinkNode levelHead = root, nextLevelHead = null;
while (levelHead != null) {
TreeLinkNode node = levelHead, tail = null;
while (node != null) {
if (node.left != null && node.right != null) {
node.left.next = node.right;
}
TreeLinkNode sub;
if (node.left != null)
sub = node.left;
else if (node.right != null)
sub = node.right;
else
sub = null;
if (sub != null) {
if (nextLevelHead == null) {
nextLevelHead = sub;
tail = sub;
} else {
tail.next = sub;
}
while (tail.next != null)
tail = tail.next;
}
node = node.next;
}
levelHead = nextLevelHead;
nextLevelHead = null;
}
}
}
``````

1.1k 声望
63 粉丝
0 条评论