From 30690fd3f8dba56797d45713e2a3b0c545d2ebce Mon Sep 17 00:00:00 2001 From: Faizansayeed28 <72259730+Faizansayeed28@users.noreply.github.com> Date: Sun, 16 Oct 2022 10:06:52 +0530 Subject: [PATCH] Implemented Level Order Traversal of a binary tree --- .../binary-tree-level-order-traversal | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Trees Algorithm/binary-tree-level-order-traversal 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 + } +};