Skip to content

Commit 8100803

Browse files
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 16.9 MB (94.54%)
1 parent ceb5c9e commit 8100803

2 files changed

Lines changed: 60 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<p>Given the <code>root</code> of a binary tree, return <em>the level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level).</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" style="width: 277px; height: 302px;" />
6+
<pre>
7+
<strong>Input:</strong> root = [3,9,20,null,null,15,7]
8+
<strong>Output:</strong> [[3],[9,20],[15,7]]
9+
</pre>
10+
11+
<p><strong class="example">Example 2:</strong></p>
12+
13+
<pre>
14+
<strong>Input:</strong> root = [1]
15+
<strong>Output:</strong> [[1]]
16+
</pre>
17+
18+
<p><strong class="example">Example 3:</strong></p>
19+
20+
<pre>
21+
<strong>Input:</strong> root = []
22+
<strong>Output:</strong> []
23+
</pre>
24+
25+
<p>&nbsp;</p>
26+
<p><strong>Constraints:</strong></p>
27+
28+
<ul>
29+
<li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li>
30+
<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>
31+
</ul>
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
vector<vector<int>> levelOrder(TreeNode* root) {
15+
vector<vector<int>> res;
16+
if (root == nullptr) return res;
17+
queue<pair<TreeNode*, int>> q;
18+
q.push({root, 0});
19+
while (!q.empty()) {
20+
auto [node, level] = q.front();
21+
q.pop();
22+
if (level == res.size()) res.push_back({});
23+
res[level].push_back(node->val);
24+
if (node->left != nullptr) q.push({node->left, level+1});
25+
if (node->right != nullptr) q.push({node->right, level+1});
26+
}
27+
return res;
28+
}
29+
};

0 commit comments

Comments
 (0)