-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTreeLevelOrderTraversalII.cpp
More file actions
42 lines (41 loc) · 1.2 KB
/
binaryTreeLevelOrderTraversalII.cpp
File metadata and controls
42 lines (41 loc) · 1.2 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
// Source: https://leetcode.com/problems/binary-tree-level-order-traversal/
// Author: Miao Zhang
// Date: 2021-01-18
/**
* 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) {
vector<vector<int>> res;
if (root == nullptr) return res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
vector<int> tmp;
for (int i = 0; i < n; i++) {
TreeNode* node = q.front();
q.pop();
tmp.push_back(node->val);
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
res.push_back(tmp);
}
reverse(res.begin(), res.end());
return res;
}
};