-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path107.cpp
49 lines (42 loc) · 1.24 KB
/
107.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
// 107. Binary Tree Level Order Traversal II - https://leetcode.com/problems/binary-tree-level-order-traversal-ii
#include "bits/stdc++.h"
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int> > result;
if (!root) { return result; }
queue<TreeNode*> q;
unordered_map<TreeNode*, int> dist;
dist[root] = 0;
q.push(root);
while(!q.empty()) {
TreeNode* cur = q.front(); q.pop();
if (result.size() <= dist[cur]) {
result.emplace_back();
}
result[dist[cur]].push_back(cur->val);
if (cur->left) {
q.push(cur->left);
dist[cur->left] = dist[cur] + 1;
}
if (cur->right) {
q.push(cur->right);
dist[cur->right] = dist[cur] + 1;
}
}
reverse(result.begin(), result.end());
return result;
}
};
int main() {
ios::sync_with_stdio(false);
return 0;
}