-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path107.二叉树的层次遍历-ii.cpp
More file actions
54 lines (52 loc) · 1.18 KB
/
Copy path107.二叉树的层次遍历-ii.cpp
File metadata and controls
54 lines (52 loc) · 1.18 KB
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
/*
* @lc app=leetcode.cn id=107 lang=cpp
*
* [107] 二叉树的层次遍历 II
*/
// @lc code=start
/**
* 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;
if (!root)
return res;
queue<TreeNode *> q;
q.push(root);
int flag = 0;
while (!q.empty())
{
vector<int> out;
int size = q.size(); //取得每一层的长度
for (int i = 0; i < size; i++)
{
auto temp = q.front();
q.pop();
out.push_back(temp->val);
if (temp->left)
{
q.push(temp->left);
}
if (temp->right)
{
q.push(temp->right);
}
}
res.push_back(out);
flag++;
}
reverse(res.begin(), res.end());
return res;
}
};
// @lc code=end