forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Populating_Next_Right_Pointers_in_Each_Node_II.cpp
49 lines (45 loc) · 1.27 KB
/
Populating_Next_Right_Pointers_in_Each_Node_II.cpp
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
44
45
46
47
48
49
/**
* 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) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
while (root) {
TreeLinkNode* sentinel = new TreeLinkNode(INT_MIN);
TreeLinkNode* currNode = sentinel;
while (root) {
if (root->left) {
currNode->next = root->left;
currNode = currNode->next;
}
if (root->right) {
currNode->next = root->right;
currNode = currNode->next;
}
root = root->next;
}
root = sentinel->next;
}
}
};
// using recursion in inorder fashion
class Solution {
public:
void flatten(TreeNode* root) {
if(!root) return;
flatten(root->left);
TreeNode* right = root->right;
root->right = root->left;
root->left = nullptr;
while(root->right) {
root = root->right;
}
root->right = right;
flatten(right);
}
};