-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path116.cpp
43 lines (35 loc) · 916 Bytes
/
116.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
#include <map>
#include <vector>
using namespace std;
// 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 {
public:
void traverse(Node* root, int depth, map<int, Node*>& link) {
if (root == nullptr) return;
auto it = link.find(depth);
if (it == link.end()) {
link.insert(make_pair(depth, root));
} else {
it->second->next = root;
it->second = root;
}
traverse(root->left, depth + 1, link);
traverse(root->right, depth + 1, link);
}
Node* connect(Node* root) {
map<int, Node*> links;
traverse(root, 0, links);
return root;
}
};