[LeetCode] Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

1
2
3
4
5
6
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Follow-up:

  • You may only use constant extra space.
  • The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
  • Time : O(hn)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;

Node() : val(0), left(NULL), right(NULL), next(NULL) {}

Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

Node(int _val, Node* _left, Node* _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
pair<bool, Node*> solution(Node* node, int currentLevel, int& targetLevel, Node* prev) {
if(!node) return {false, NULL};
if(currentLevel < targetLevel) {
auto [resultLeft, leftPrevNode] = solution(node->left, currentLevel + 1, targetLevel, prev);
if(!resultLeft) return {false, NULL};
auto [resultRight, rightPrevNode] = solution(node->right, currentLevel + 1, targetLevel, leftPrevNode);
return {resultRight, rightPrevNode};
} else {
if(prev) prev->next = node;
return {true, node};
}
}

public:
Node* connect(Node* root) {
int level = 1;
while (true) {
auto [result, _] = solution(root, 0, level, nullptr);
if(!result) break;
level++;
}
return root;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/populating-next-right-pointers-in-each-node/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.