#include #include using namespace std; template class BinaryTreeNode { public: T data; BinaryTreeNode* left; BinaryTreeNode* right; BinaryTreeNode(T data){ this->data=data; left=NULL; right=NULL; } ~BinaryTreeNode(){ delete left; delete right; } }; int height(BinaryTreeNode* root){ if(root==NULL){ return 0; } return 1+max(height(root->left),height(root->right)); } //calculating diameter of treenode int diameter(BinaryTreeNode* root) { if(root==NULL){ return 0; } int option1=height(root->left)+height(root->right); int option2=diameter(root->left); int option3=diameter(root->right); return max(option1,max(option2,option3)); } //heightDiameter- this function is used for better approach in diameter function pair heightDiameter(BinaryTreeNode* root){ if(root==NULL){ pair p; p.first=0; p.second=0; return p; } pair leftAns=heightDiameter(root->left); pair rightAns=heightDiameter(root->right); int ld=leftAns.second; int lh=leftAns.first; int rd=rightAns.second; int rh=rightAns.first; int height=1+max(lh,rh); int diameter = max(lh+rh,max(ld,rd)); pair p; p.first=height; p.second=diameter; return p; } //printing binary tree void printTree(BinaryTreeNode* root) { if(root==NULL) return; cout<data<<":"; if(root->left){ cout<<"L"<left->data<<" "; } if(root->right){ cout<<"R"<right->data<<" "; } cout<left); printTree(root->right); } //taking input level wise BinaryTreeNode* takeInputLevelwise(){ int rootData; cout<<"Enter root data"<>rootData; if(rootData==-1) return NULL; BinaryTreeNode* root = new BinaryTreeNode(rootData); queue*> pendingNodes; pendingNodes.push(root); while(pendingNodes.size() != 0){ BinaryTreeNode* front = pendingNodes.front(); pendingNodes.pop(); cout<<"Enter left child of "<data<>leftChildData; if(leftChildData!=-1){ BinaryTreeNode* child = new BinaryTreeNode(leftChildData); front->left=child; pendingNodes.push(child); } cout<<"Enter right child of "<data<>rightChildData; if(rightChildData!=-1){ BinaryTreeNode* child = new BinaryTreeNode(rightChildData); front->right=child; pendingNodes.push(child); } } return root; } //counting nodes int numNodes(BinaryTreeNode* root){ if(root==NULL) return 0; return 1+numNodes(root->left)+numNodes(root->right); }; // 1 2 3 4 5 6 7 -1 -1 -1 -1 8 9 -1 -1 -1 -1 -1 -1 int main() { //levelwise input BinaryTreeNode* root=takeInputLevelwise(); printTree(root); cout<<"Total number of nodes: "< p = heightDiameter(root); cout<<"Height: "<