forked from keineahnung2345/leetcode-cpp-practices
-
Notifications
You must be signed in to change notification settings - Fork 0
/
102. Binary Tree Level Order Traversal.cpp
42 lines (34 loc) · 1.23 KB
/
102. Binary Tree Level Order Traversal.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
//BFS
//Runtime: 4 ms, faster than 88.94% of C++ online submissions for Binary Tree Level Order Traversal.
//Memory Usage: 13 MB, less than 17.26% of C++ online submissions for Binary Tree Level Order Traversal.
/**
* Definition for a binary tree node.
* 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) {
queue<TreeNode*> q;
vector<vector<int>> ans;
if(root) q.push(root);
while(!q.empty()){
int level_size = q.size();
vector<int> level;
while(level_size-- > 0){
TreeNode* cur = q.front(); q.pop();
level.push_back(cur->val);
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
ans.push_back(level);
}
return ans;
}
};