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
131 changes: 131 additions & 0 deletions Level Order Traversal in Binary Tree
Original file line number Diff line number Diff line change
@@ -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<queue>
class Solution
{
public:
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>>ans;

if(root==NULL)
return ans;

//creating a queue for level order traversal
queue<TreeNode*>q;

//pushing the root node
q.push(root);

while(!q.empty())
{
//creating a vector to store the elements at a particular level
vector<int>level;
//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<vector<int>> levelOrderBottom(TreeNode* root)
{
vector<vector<int>>ans;

if(root==NULL)
return ans;

queue<TreeNode*>q;
q.push(root);

while(!q.empty())
{
vector<int>levelb;
int size=q.size();

for(int i=0;i<size;i++)
{
TreeNode*temp=q.front();
q.pop();
levelb.push_back(temp->val);

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]]