jain12

diameter of a binary tree in linear time complexity

Mar 8th, 2020
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. class Node{
  5.   public:
  6.       int data;
  7.       Node *left,*right;
  8.       Node(int key){
  9.         data=key;
  10.         left=NULL;
  11.         right=NULL;
  12.         }
  13.   };
  14.  
  15. void preorder(Node *root){
  16.   if(root==NULL)
  17.      return;
  18.   cout<<" "<<root->data;
  19.   preorder(root->left);
  20.   preorder(root->right);
  21.   }
  22.  
  23. int Height(Node *node_ptr,int &dia){
  24.   if(node_ptr==NULL)
  25.     return 0;
  26.   int left_height= Height(node_ptr->left,dia);
  27.   int right_height=Height(node_ptr->right,dia);
  28.   dia=max(dia,left_height+right_height+1);
  29.   return max(left_height,right_height)+1;
  30.   }
  31.  
  32. int DiameterOfTree(Node * root){
  33.   if(root==NULL)
  34.    return 0;
  35.   int diameter=INT_MIN;
  36.   Height(root,diameter);
  37.    return diameter;
  38.   }
  39.  
  40. int main(){
  41.   Node *root=NULL;
  42.   Node *newnode=new Node(1);
  43.   root=newnode;
  44.   root->left=new Node(2);
  45.   root->right=new Node(3);
  46.   (root->left)->left=new Node(4);
  47.   (root->right)->right=new Node(5);
  48.   cout<<"pre order traversal ";
  49.   preorder(root);
  50.   cout<<endl<<DiameterOfTree(root);
  51.   return 0;
  52.   }
Add Comment
Please, Sign In to add comment