-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopulating_next_right_pointers.cpp
More file actions
109 lines (96 loc) · 2.1 KB
/
populating_next_right_pointers.cpp
File metadata and controls
109 lines (96 loc) · 2.1 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// =====================================================================================
//
// Filename: populating_next_right_pointers.cpp
//
// Description: 116. Populating Next Right Pointers in Each Node.
//
// Version: 1.0
// Created: 08/15/2019 05:30:52 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
// Organization:
//
// =====================================================================================
#include <stdio.h>
// Definition for a Node.
struct Node
{
int val;
Node* left;
Node* right;
Node* next;
Node() {}
Node(int _val, Node* _left, Node* _right, Node* _next)
{
val = _val;
left = _left;
right = _right;
next = _next;
}
};
// Recursive
class Solution1
{
public:
Node* connect(Node* root)
{
if (root != nullptr)
{
connect(root->left, root->right);
}
return root;
}
private:
void connect(Node* lnode, Node* rnode)
{
if (lnode == nullptr)
{
return;
}
lnode->next = rnode;
connect(lnode->left, lnode->right);
if (rnode != nullptr)
{
connect(lnode->right, rnode->left);
connect(rnode->left, rnode->right);
}
}
};
// Iterative
class Solution2
{
public:
Node* connect(Node* root)
{
if (root == nullptr)
{
return root;
}
Node* pre = root;
Node* cur = nullptr;
while (pre->left != nullptr)
{
cur = pre;
while (cur != nullptr)
{
cur->left->next = cur->right;
if (cur->next != nullptr)
{
cur->right->next = cur->next->left;
}
cur = cur->next;
}
pre = pre->left;
}
return root;
}
};
using Solution = Solution2;
int main(int argc, char* argv[])
{
Node* root = nullptr;
root = Solution().connect(root);
return 0;
}