-
Notifications
You must be signed in to change notification settings - Fork 0
/
102_levelOrder.txt
55 lines (55 loc) · 1.67 KB
/
102_levelOrder.txt
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
55
/**
* 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>> levelOrder(TreeNode* root) {
// if(root == NULL)
// return {};
// vector<vector<int>> res;
// helper(res,root,0);
// return res;
// }
// void helper(vector<vector<int>>& res,TreeNode* p,int level){
// if(p == NULL)
// return;
// if(level>=res.size()){
// vector<int> temp;
// res.push_back(temp);
// }
// res[level].push_back(p->val);
// if(p->left!=NULL)
// helper(res,p->left,level+1);
// if(p->right!=NULL)
// helper(res,p->right,level+1);
// }
vector<vector<int>> levelOrder(TreeNode* root){
if(root == NULL)
return {};
vector<vector<int>> res;
queue<TreeNode*> helper;//辅助队列每次只存放该层的所有元素
TreeNode* p;
helper.push(root);//将根节点入队
while(helper.empty()==0){//队列不空
vector<int> temp;
int size = helper.size();
for(int i = 0;i < size;i++){//将本层的元素全部加入到temp中并把下一层元素加入队列中
p = helper.front();
temp.push_back(p->val);
helper.pop();
if(p->left)
helper.push(p->left);
if(p->right)
helper.push(p->right);
}
res.push_back(temp);
}
return res;
}
};