Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions Trees Algorithm/binary-tree-level-order-traversal
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> answer;
if(!root) return answer; //if root is NULL then return
queue<TreeNode*> q; //for storing nodes
q.push(root); //push root initially to the queue
while(!q.empty()) //while queue is not empty go and follow few steps
{
int size=q.size(); //storing queue size for while loop
vector<int> v; //for storing nodes at the same level
while(size--)
{
TreeNode* temp=q.front(); //store front node of queue and pop it from queue
q.pop();
v.push_back(temp->val); //push it to v
if(temp->left) q.push(temp->left); //if left subtree exist for temp then store it into the queue
if(temp->right) q.push(temp->right); //if right subtree exist for temp then store it into the queue
}
answer.push_back(v); //push v into answer, as v consist of all the nodes of current level
}
return answer; //return the answer
}
};