forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain3.cpp
58 lines (43 loc) · 1.25 KB
/
main3.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
50
51
52
53
54
55
56
57
58
/// Source : https://leetcode.com/problems/populating-next-right-pointers-in-each-node/description/
/// Author : liuyubobobo
/// Time : 2018-10-19
#include <iostream>
#include <queue>
#include <cassert>
using namespace std;
/// BFS without queue
/// Since the upper level have already been a linked list
/// We can traverse the upper level in a linked list way to connect the lower level
/// Actually, the upper linked list is our queue :-)
///
/// Time Complexity: O(n)
/// Space Compelxity: O(1)
/// 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) {
if(!root) return;
while(root->left){
TreeLinkNode* p = root;
TreeLinkNode* dummyHead = new TreeLinkNode(-1);
TreeLinkNode* cur = dummyHead;
while(p){
cur->next = p->left;
cur = cur->next;
cur->next = p->right;
cur = cur->next;
p = p->next;
}
delete dummyHead;
root = root->left;
}
}
};
int main() {
return 0;
}