Skip to content

Commit b5d7db0

Browse files
authored
Add files via upload
1 parent 6fd46f8 commit b5d7db0

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
16+
vector<vector<int>> result;
17+
if(!root) return result; // return nothing if the root is nullptr
18+
19+
queue<TreeNode*>q;
20+
q.push(root);
21+
22+
// continue the process untill there is no node
23+
while(!q.empty())
24+
{
25+
int size = q.size();
26+
vector<int> level;
27+
28+
// run the loop to process each node
29+
for (int i=0; i<size;i++)
30+
{
31+
/// Get the next node from the front of the queue.
32+
TreeNode* node=q.front();
33+
q.pop();
34+
level.push_back(node->val);
35+
// if the curent node has a left child
36+
if(node->left) q.push(node->left);
37+
38+
if(node-> right) q.push(node-> right);
39+
}
40+
result.push_back(level);
41+
}
42+
43+
return result;
44+
}
45+
};

0 commit comments

Comments
 (0)