Solution1: O(N) O(N)
Level order traversal
class Solution {
public Node connect(Node root) {
if (root == null) {
return root;
}
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
Node node = queue.poll();
if (i != size - 1) {
node.next = queue.peek();
}
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
return root;
}
}
Solution2 : O(N) O(1)
- when we go over the nodes of a particular level, their next pointers are already established.
- This is what helps get rid of the queue data structure from the previous approach and helps save space.
- There are two types of
nextconnextions.- Under the same parent.
- Between different parents
class Solution {
public Node connect(Node root) {
if (root == null) {
return root;
}
// first Node at current level
Node start = root;
// loop over each level
while (start.left != null) {
Node cur = start;
// traverse the cur level linkedlist, and connect the next level nodes
while (cur != null) {
// type1, two next level nodes share same parent
cur.left.next = cur.right;
// type2, two next level nodes have different parent
if (cur.next != null) {
cur.right.next = cur.next.left;
}
cur = cur.next;
}
// move to next level
start = start.left;
}
return root;
}
}