diff --git a/Trees Algorithm/binary-tree-level-order-traversal b/Trees Algorithm/binary-tree-level-order-traversal new file mode 100644 index 00000000..0b886d4e --- /dev/null +++ b/Trees Algorithm/binary-tree-level-order-traversal @@ -0,0 +1,24 @@ +class Solution { +public: + vector> levelOrder(TreeNode* root) { + vector> answer; + if(!root) return answer; //if root is NULL then return + queue 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 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 + } +};