[Geeks for Geeks] Connect Nodes at Same Level

Connect Nodes at Same Level
>

  • Time : O(n)
  • Space : O(d)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution
{
vector<Node*> lvl;
public:
//Function to connect nodes at same level.
void connect(Node *root, int dep = 0)
{
if(!root) return;
if(lvl.size() == dep)
lvl.push_back(root);
else {
lvl[dep]->nextRight = root;
lvl[dep] = root;
}
connect(root->left, dep + 1);
connect(root->right, dep + 1);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/connect-nodes-at-same-level/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.