Skip to content

Commit

Permalink
Added Question in Love Babbar DSA Sheet
Browse files Browse the repository at this point in the history
  • Loading branch information
KaranSiddhu committed Dec 1, 2021
1 parent ffbde4a commit b989b6c
Show file tree
Hide file tree
Showing 5 changed files with 108 additions and 0 deletions.
1 change: 1 addition & 0 deletions Love Babbar DSA Sheet/2. Matrix/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Coming soon
1 change: 1 addition & 0 deletions Love Babbar DSA Sheet/3. String/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Coming soon
1 change: 1 addition & 0 deletions Love Babbar DSA Sheet/4. Searching & Sorting/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Coming soon
1 change: 1 addition & 0 deletions Love Babbar DSA Sheet/5. LinkedList/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Coming soon
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
#include <bits/stdc++.h>
using namespace std;

/*Ques - Given a binary tree of size N, find its reverse level order traversal. ie- the traversal must begin from the last level.
Input - 1 3 2 -1 -1 -1 -1
Output - 3 2 1
*/

class Node{
public:
int data;
Node *left;
Node *right;

Node(int data){
this->data = data;
left = right = NULL;
}

~Node(){
delete left;
delete right;
}
};

Node *buildBinaryTree(){
int rootData;
cout << "Enter root data - ";
cin >> rootData;

Node *root = new Node(rootData);

queue<Node *> pendingNodes;
pendingNodes.push(root);

while (!pendingNodes.empty()){
Node *front = pendingNodes.front();
pendingNodes.pop();

int leftData;
cout << "Enter Left Child of " << front->data << "\n";
cin >> leftData;

if (leftData != -1){
Node *leftChild = new Node(leftData);
front->left = leftChild;
pendingNodes.push(leftChild);
}

int rightData;
cout << "Enter Right Child of " << front->data << "\n";
cin >> rightData;

if (rightData != -1){
Node *rightChild = new Node(rightData);
front->right = rightChild;
pendingNodes.push(rightChild);
}
}

return root;
}

vector<int> reverseLevelOrder(Node *root){
vector<int> ans;
stack<Node *> s;
queue<Node *> q;
q.push(root);

while (!q.empty()){
Node *front = q.front();
q.pop();
s.push(front);

if (front->right)
q.push(front->right);

if (front->left)
q.push(front->left);
}

while (!s.empty()){
Node *temp = s.top();
ans.push_back(temp->data);
s.pop();
}

return ans;
}

int main(){

Node *root = buildBinaryTree();

vector<int> ans = reverseLevelOrder(root);

for(int e : ans)
cout << e << " ";

delete root;
return 0;
}

0 comments on commit b989b6c

Please sign in to comment.