diff --git a/Level Order Traversal in Binary Tree b/Level Order Traversal in Binary Tree new file mode 100644 index 0000000..85c93e5 --- /dev/null +++ b/Level Order Traversal in Binary Tree @@ -0,0 +1,131 @@ +LEVEL ORDER TRAVERSAL +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +#include +class Solution +{ + public: + vector> levelOrder(TreeNode* root) + { + vector>ans; + + if(root==NULL) + return ans; + + //creating a queue for level order traversal + queueq; + + //pushing the root node + q.push(root); + + while(!q.empty()) + { + //creating a vector to store the elements at a particular level + vectorlevel; + //extracting the front node from the queue + TreeNode* temp= q.front(); + q.pop(); + + //storing the front node data in level + level.push_back(temp->val); + + //if the front node has left or right or both child push them in the queue + if(temp->left) + q.push(temp->left); + + if(temp->right) + q.push(temp->right); + + //now push all the node data at a particular level in ans vector + ans.push_back(level); + } + + //return ans + return ans; + } +}; + +Test Cases: +Input: root = [3,9,20,null,null,15,7] +Output: [[3],[9,20],[15,7]] + +Input: root = [1] +Output: [[1]] + +Input: root = [] +Output: [] + + + +//Code for REVERSER LEVEL ORDER TRAVERSAL +/* +logic for this is quiet similar to the level order traversal the only difference is that we have to push right child first then left child and +at the end we have to reverser the level vector before pushing it in ans vector +*/ + + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> levelOrderBottom(TreeNode* root) + { + vector>ans; + + if(root==NULL) + return ans; + + queueq; + q.push(root); + + while(!q.empty()) + { + vectorlevelb; + int size=q.size(); + + for(int i=0;ival); + + if(temp->right) + q.push(temp->right); + + if(temp->left) + q.push(temp->left); + } + reverse(levelb.begin(),levelb.end()); + ans.push_back(levelb); + } + reverse(ans.begin(),ans.end()); + + + return ans; + } +}; + +Test Cases: +Input: root = [3,9,20,null,null,15,7] +Output: [[15,7],[9,20],[3]] + +Input: root = [1] +Output: [[1]]