-
Notifications
You must be signed in to change notification settings - Fork 0
/
107. 二叉树的层次遍历II.cc
47 lines (43 loc) · 1.12 KB
/
107. 二叉树的层次遍历II.cc
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root)
{
vector<vector<int>> res;
stack<vector<int>> sres;
if(root == nullptr) return res;
std::queue<TreeNode *> qtree;
qtree.push(root);
vector<int> subRes;
while(!qtree.empty())
{
int size = qtree.size();
subRes.clear();
for(int i=0; i<size; ++i)
{
TreeNode *node = qtree.front();
qtree.pop();
subRes.push_back(node->val);
if(node->left) qtree.push(node->left);
if(node->right) qtree.push(node->right);
}
sres.push(subRes);
}
/* reverse */
while(!sres.empty())
{
const vector<int> &tmp = sres.top();
res.emplace_back(std::move(tmp));
sres.pop();
}
return res;
}
};