
Please wait a little bit, we are fetching the blogs from the database ....

Please wait a little bit, we are fetching the blogs from the database ....
Summary for the blog ⌨️⌨️ : In this blog we will cover some problems related to trees and their different traversals.
| Sl No | problems/ Algorithms | Link |
|---|---|---|
| 1 | Zig zag traversal | Problem 1 |
| 2 | Boundary traversal | Problem 2 |
Explanation :-
class Solution{
public:
vector<int> solve(Node* root){
queue<Node*>q;
q.push(root);
bool leftToright =true;
vector<int>res;
while(!q.empty()){
int size =q.size();
vector<int>ans(size);
for(int i=0;i<size;i++){
Node* temp = q.front();
q.pop();
int index = leftToright?i:size-i-1;
ans[index]=temp->data;
if(temp->left){
q.push(temp->left);
}
if(temp->right){
q.push(temp->right);
}
}
leftToright=!leftToright;
for(auto i:ans){
res.push_back(i);
}
}
return res;
}
//Function to store the zig zag order traversal of tree in a list.
vector <int> zigZagTraversal(Node* root)
{
// Code here
return solve(root);
}
};
Explanation :-
class Solution {
public:
void leftsolve(Node*root,vector<int> &ans){
if(root==NULL || (root->left==NULL &&root->right==NULL)){
return;
}
ans.push_back(root->data);
if(root->left){
leftsolve(root->left,ans);
}
else{
leftsolve(root->right,ans);
}
}
void leafsolve(Node*root,vector<int>& ans){
if(root==NULL){
return;
}
if(root->left==NULL &&root->right==NULL){
ans.push_back(root->data);
return;
}
leafsolve(root->left,ans);
leafsolve(root->right,ans);
}
void rightsolve(Node*root,vector<int>& ans){
if(root==NULL || (root->left==NULL &&root->right==NULL)){
return;
}
if(root->right){
rightsolve(root->right,ans);
}
else{
rightsolve(root->left,ans);
}
ans.push_back(root->data);
}
vector <int> boundary(Node *root)
{
//Your code here
vector<int>ans;
ans.push_back(root->data);
leftsolve(root->left,ans);
leafsolve(root->left,ans);
leafsolve(root->right,ans);
rightsolve(root->right,ans);
return ans;
}
};