Description
Given the root
of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Constraints:
- The number of nodes in the tree is in the range
[0, 2000]
. -1000 <= Node.val <= 1000
Solution
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
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<int> row;
vector<vector<int>> result;
queue<TreeNode*> q;
if (root == NULL)
return result;
q.push(root);
while (q.size() > 0) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
TreeNode* node = q.front();
q.pop();
row.push_back(node->val);
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
}
result.push_back(row);
row.clear();
}
return result;
}
};
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Binary Tree Level Order Traversal.
Memory Usage: 12.4 MB, less than 96.11% of C++ online submissions for Binary Tree Level Order Traversal.