Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 24fec59

Browse files
committedJun 15, 2023
Level order traversal
1 parent ffea094 commit 24fec59

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
 
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
queue<TreeNode*> q;
17+
vector<vector<int>> toreturn;
18+
if(root==NULL)
19+
{
20+
return toreturn;
21+
}
22+
q.push(root);
23+
24+
while(!q.empty())
25+
{
26+
int size = q.size();
27+
vector<int> level;
28+
for(int i = 0;i<size;i++)
29+
{
30+
level.push_back(q.front()->val);
31+
if(q.front()->left)
32+
{
33+
q.push(q.front()->left);
34+
}
35+
if(q.front()->right)
36+
{
37+
q.push(q.front()->right);
38+
}
39+
q.pop();
40+
}
41+
toreturn.push_back(level);
42+
}
43+
44+
return toreturn;
45+
}
46+
};

0 commit comments

Comments
 (0)
Please sign in to comment.