SCHOOL OF CODE BUILDERS
Learn To CODE. Become A DEVELOPER.
Pages
HOME
DATA STRUCTURES
STRINGS
ARRAYS
MATRIX
BINARY TREES
LINKED LIST
STACK
QUEUE
SORTING
SEARCHING
C
PYTHON
PSEUDOCODE
CONTEST PROBLEMS
ALGORITHMS
PATTERNS
PHP
C PUZZLES
C INTERVIEW QUESTIONS
JAVA
C++
HASHING
RECURSION
BASIC C PROGRAMS
TCS-CODEVITA
FACEBOOK
CONTACT US
Find the Diameter of the Binary Tree
Find the Diameter of the Binary Tree
#include
#include
#include
int lminheight=INT_MAX,rmaxheight=INT_MIN; struct node { int data; struct node *left,*right; }; struct node* insert(int data) { struct node *temp=(struct node*)malloc(sizeof(struct node)); temp->data=data; temp->left=temp->right=NULL; return temp; } void inorder(struct node *root) { if(root==NULL) return; inorder(root->left); printf("%d ",root->data); inorder(root->right); } int diameter(struct node *root,int height) { if(root==NULL) return 0; diameter(root->left,height-1); lminheight=lminheight
right,height+1); rmaxheight=rmaxheight>height?rmaxheight:height; return (abs(rmaxheight)+abs(lminheight))+1; } int main(void) { struct node *root=NULL; int *path,pathlen; int height=0; path=(int*)malloc(sizeof(int)*1000); root=insert(1); root->left=insert(2); root->left->left=insert(4); root->left->right=insert(5); root->left->left->left=insert(8); root->left->left->right=insert(9); root->left->right->left=insert(10); root->left->right->right=insert(11); root->right=insert(3); root->right->left=insert(6); root->right->right=insert(7); root->right->left->left=insert(12); root->right->left->right=insert(13); root->right->right->left=insert(14); root->right->right->right=insert(15); //inorder(root); printf("diameter of the tree is %d",diameter(root,height)); return 0; }
PREVIOUS
NEXT
HOME