-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_tree_level_order_102.cpp
42 lines (36 loc) · 1.06 KB
/
binary_tree_level_order_102.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
//
// Created by 王月艺 on 2022/2/1.
//
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ret;
if(root == nullptr){
return ret;
}
queue<TreeNode*> que;
que.push(root);
while(!que.empty()){
int levelNodeNums = que.size();
ret.push_back(vector<int> ());
for(int i=0; i<levelNodeNums; ++i){
TreeNode* frontNode = que.front();
que.pop();
ret.back().push_back(frontNode->val);
if(frontNode->left) que.push(frontNode -> left);
if(frontNode->right) que.push(frontNode -> right);
}
}
return ret;
}
};