
Sponsored
Sponsored
This approach uses a breadth-first search (BFS) strategy by employing a queue to keep track of nodes at the current level and connect their children nodes from left to right. After processing all nodes on a level, we move to the children (if any), ensuring the next pointers are correctly set.
Time Complexity: O(n), where n is the number of nodes in the tree since each node is enqueued and dequeued once.
Space Complexity: O(n) for the queue in the worst case where the last level of the tree has a maximum number of nodes.
1import java.util.LinkedList;
2import java.util.Queue;
3
4class Node {
5 public int val;
6 public Node left;
7 public Node right;
8 public Node next;
9
10 public Node() {}
11
12 public Node(int _val) {
13 val = _val;
14 }
15
16 public Node(int _val, Node _left, Node _right, Node _next) {
17 val = _val;
18 left = _left;
19 right = _right;
20 next = _next;
21 }
22}
23
24class Solution {
25 public void connect(Node root) {
26 if (root == null) return;
27 Queue<Node> queue = new LinkedList<>();
28 queue.add(root);
29 while (!queue.isEmpty()) {
30 int size = queue.size();
31 Node prev = null;
32 for (int i = 0; i < size; i++) {
33 Node curNode = queue.poll();
34 if (prev != null) prev.next = curNode;
35 prev = curNode;
36 if (curNode.left != null) queue.add(curNode.left);
37 if (curNode.right != null) queue.add(curNode.right);
38 }
39 }
40 }
41}
42This solution utilizes a queue to maintain the nodes at the current level. As nodes are processed, their children are enqueued, ensuring a level-order sequence of connections. Each node's next is set to the next node in the queue.
This approach leverages a two-pointer or head-tail strategy to eliminate the need for extra storage space beyond two pointers. The idea is to work with two nested loops; an outer loop goes level by level, and an inner loop connects nodes within the same level by their next pointers.
Time Complexity: O(n) since each node is processed once.
Space Complexity: O(1), only utilizing a few pointers.
This JavaScript solution iterates through each level, dynamically constructing the next connections by organizing two pointer variables and minimizing space overhead beyond initial construction.