-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path102.cpp
51 lines (41 loc) · 1.22 KB
/
102.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
// 102. Binary Tree Level Order Traversal - https://leetcode.com/problems/binary-tree-level-order-traversal
#include "bits/stdc++.h"
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
private:
vector<vector<int> > answer;
unordered_map<TreeNode*, int> dist;
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if (root == nullptr) { return answer; }
queue<TreeNode*> q;
q.push(root);
dist[root] = 0;
while(!q.empty()) {
TreeNode* node = q.front(); q.pop();
if ((int)answer.size() <= dist[node]) {
answer.push_back({});
}
answer[dist[node]].emplace_back(node->val);
if (node->left != nullptr) {
dist[node->left] = dist[node] + 1;
q.push(node->left);
}
if (node->right != nullptr) {
dist[node->right] = dist[node] + 1;
q.push(node->right);
}
}
return answer;
}
};
int main() {
ios::sync_with_stdio(false);
return 0;
}