jain12

deepest node in binary tree

Feb 29th, 2020
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.03 KB | None | 0 0
  1. #include<iostream>
  2. #include<queue>
  3. #include<stack>
  4. using namespace std;
  5.  
  6. class Node{
  7.   public:
  8.       int data;
  9.       Node *left,*right;
  10.       Node(int key){
  11.         data=key;
  12.         left=NULL;
  13.         right=NULL;
  14.         }
  15.   };
  16.  
  17. void PrintDeepestNode(Node *root){
  18. if(root==NULL)
  19.    return ;
  20. queue<Node*>q;
  21. stack<Node *>s;
  22. q.push(root);
  23. q.push(NULL);
  24. while(!q.empty()){
  25.   Node *temp=q.front();
  26.   q.pop();
  27.   if(temp!=NULL){
  28.      s.push(temp);
  29.      if(temp->right!=NULL)
  30.         q.push(temp->right);
  31.      if(temp->left!=NULL)
  32.         q.push(temp->left);
  33.      }
  34.   else
  35.     if(q.size()>0){
  36.          q.push(NULL);
  37.          s.push(NULL);
  38.          }
  39.    }
  40. while(s.top()!=NULL){
  41.   cout<<" "<<(s.top())->data;
  42.   s.pop();
  43.   }
  44. }
  45.  
  46. int main(){
  47.   Node *root=NULL;
  48.   Node *newnode=new Node(1);
  49.   root=newnode;
  50.   root->left=new Node(2);
  51.   root->right=new Node(3);
  52.   (root->left)->left=new Node(4);
  53.   (root->right)->right=new Node(5);
  54.   ((root->left)->left)->left=new Node(6);
  55.   PrintDeepestNode(root);
  56.   return 0;
  57.   }
Add Comment
Please, Sign In to add comment