[InterviewBit] Populate Next Right Pointers Tree

Populate Next Right Pointers Tree

  • Time : O(n)
  • Space : O(logn)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
void Solution::connect(TreeLinkNode* A) {
queue<TreeLinkNode*> Q;
Q.push(A);
while(!Q.empty()) {
int sz = Q.size();
while(sz--) {
auto u = Q.front(); Q.pop();
if(sz) u->next = Q.front();
if(u->left) Q.push(u->left);
if(u->right) Q.push(u->right);
}
}
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/01/PS/interviewbit/populate-next-right-pointers-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.