
Solution1 level order traversal O(N)O(N)
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: using established linkedlist O(N)O(1)
- since we dont know the structure of the tree/next level, we can know where it start. s
- so we use a dummy head for next level.
class Solution {
public Node connect(Node root) {
if (root == null) {
return root;
}
Node start = root;
while (start != null) {
Node cur = start;
Node dummy = new Node();
Node nextLvCur = dummy;
while (cur != null) {
if (cur.left != null) {
nextLvCur.next = cur.left;
nextLvCur = nextLvCur.next;
}
if (cur.right != null) {
nextLvCur.next = cur.right;
nextLvCur = nextLvCur.next;
}
cur = cur.next;
}
start = dummy.next;
}
return root;
}
}