1. BFS Queue Level Order Traversal
Intuition
Push root to queue. For each level of size S, pop node and wire node.next to queue.front() for all except last element.
When to apply: Basic baseline check.
Algorithm
- Step 1: If root == null return null.
- Step 2: Queue q with root.
- Step 3: Pop node; if i < sz - 1: node.next = q.front().
- Step 4: Push non-null children.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: Node* connect(Node* root) { if (!root) return nullptr; queue<Node*> q; q.push(root); while (!q.empty()) { int sz = q.size(); for (int i = 0; i < sz; ++i) { Node* cur = q.front(); q.pop(); if (i < sz - 1) cur->next = q.front(); if (cur->left) q.push(cur->left); if (cur->right) q.push(cur->right); } } return root; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Every node visited once. - Space complexity:
O(w)— Queue holds level width w.