117. Populating Next Right Pointers in Each Node II
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
1 ->NULL
/ \
2 -> 3 ->NULL
/ \ \
4-> 5 -> 7 ->NULL
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null) {
return;
}
Queue<TreeLinkNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeLinkNode curNode = queue.remove();
if (i == size - 1) {
curNode.next = null;
}
else {
curNode.next = queue.peek();
}
if (curNode.left != null) {
queue.add(curNode.left);
}
if (curNode.right != null) {
queue.add(curNode.right);
}
}
}
}
}
public class Solution {
public void connect(TreeLinkNode root) {
TreeLinkNode preNode = null, curNode = root, leftMostNode = null;
while (curNode != null) {
while (curNode != null) {
if (curNode.left != null) {
if (preNode != null) {
preNode.next = curNode.left;
}
else {
leftMostNode = curNode.left;
}
preNode = curNode.left;
}
if (curNode.right != null) {
if (preNode != null) {
preNode.next = curNode.right;
}
else {
leftMostNode = curNode.right;
}
preNode = curNode.right;
}
curNode = curNode.next;
}
curNode = leftMostNode;
preNode = null;
leftMostNode = null;
}
}
}
3. Time & Space Complexity