From 5bcb82016d635d2c7d7abc4c48c917455989e035 Mon Sep 17 00:00:00 2001 From: shikhar9820 <36673214+shikhar9820@users.noreply.github.com> Date: Thu, 31 Oct 2019 23:13:48 +0530 Subject: [PATCH] Trees --- trees | 208 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 208 insertions(+) create mode 100644 trees diff --git a/trees b/trees new file mode 100644 index 0000000..1bd781a --- /dev/null +++ b/trees @@ -0,0 +1,208 @@ + + +#include +using namespace std; + +class node +{ +public: + int data; + node* left; + node* right; + + node(int d) + { + data=d; + left=NULL; + right=NULL; + } +}; + +node* createTree() +{ + + int d; + cin>>d; + + if(d==-1) + { + return NULL; + } + + node* root=new node(d); + cout<<"enter left child of "<left=createTree(); + cout<<"enter right child of "<right=createTree(); + + return root; + +} + +void preOrder(node* root) +{ + if(root==NULL) + { + return; + } + + cout<data<<" "; + preOrder(root->left); + preOrder(root->right); +} + +void postOrder(node* root) +{ + if(root==NULL) + { + return; + } + + postOrder(root->left); + postOrder(root->right); + cout<data<<" "; +} + +void inOrder(node* root) +{ + if(root==NULL) + { + return; + } + + inOrder(root->left); + cout<data<<" "; + inOrder(root->right); +} + +int height(node* root) +{ + if(root==NULL) + { + return 0; + } + + int leftChildHeight=height(root->left); + int rightChildHeight=height(root->right); + + int h=max(leftChildHeight,rightChildHeight)+1; + return h; +} + +int count(node* root) +{ + if(root==NULL) + { + return 0; + } + + int leftCount=count(root->left); + int rightCount=count(root->right); + + int totalCount=leftCount+rightCount+1; + return totalCount; +} + +int diameter(node* root) +{ + if(root==NULL) + { + return 0; + } + + int op1=height(root->left)+height(root->right); + int op2=diameter(root->left); + int op3=diameter(root->right); + + int ans=max(op1,max(op2,op3)); + return ans; +} + +class Pair +{ +public: + int Height; + int Diameter; +}; + + +Pair fastDiameter(node* root) +{ + Pair p; + if(root==NULL) + { + p.Height=0; + p.Diameter=0; + return p; + } + + Pair left=fastDiameter(root->left); + Pair right=fastDiameter(root->right); + + p.Height=max(left.Height,right.Height)+1; + + int op1=left.Height+right.Height; + int op2=left.Diameter; + int op3=right.Diameter; + + p.Diameter=max(op1,max(op2,op3)); + + return p; + + +} + + + +int main() +{ + + node *root=createTree(); + + cout<<"preOrder traversal is : "; + preOrder(root); + cout<