-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode_107
53 lines (52 loc) · 1.59 KB
/
leetcode_107
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
/**
* 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>> ans;
if(!root)
return ans;
vector<int> root_vec;
root_vec.push_back(root->val);
ans.push_back(root_vec);
//用队列存节点,每次把节点都弹空,再压入下一层的节点
queue<TreeNode*> que;
que.push(root);
while(!que.empty())//每次执行这个循环代表进入下一层
{
vector<int> tmp_vec;
vector<TreeNode*> tmp_node;
while(!que.empty())//计算其子节点
{
TreeNode* tmp=que.front();
que.pop();
if(tmp->left)
{
tmp_vec.push_back(tmp->left->val);
tmp_node.push_back(tmp->left);
}
if(tmp->right)
{
tmp_vec.push_back(tmp->right->val);
tmp_node.push_back(tmp->right);
}
}
//cout<<tmp_node.size()<<endl;
if(!tmp_vec.empty())
ans.push_back(tmp_vec);
for(int i=0;i<tmp_node.size();i++)
que.push(tmp_node[i]);
}
vector<vector<int>> vec_ans;
for(int i=ans.size()-1;i>=0;i--)
vec_ans.push_back(ans[i]);
return vec_ans;
}
};