Pages

Subscribe:

Blogger templates

Saturday, July 16, 2016

Height of Tree | Easiest Implimentation

There are many approaches to find the height of the TREE







Height 3


#include<stdio.h>
#include<stdlib.h>
struct node{
    int data;
    struct node *right,*left;
}*root=NULL;
int max=0;
struct node *newnode(int k){
    struct node *temp=(struct node *)malloc(sizeof(struct node));
    temp->data=k;
    temp->right=temp->left=NULL;
    return temp;
}
void height(struct node *root,int d){
    if(root==NULL){
        return;
    }
    printf("Node:%d,Height: %d\n",root->data,d);
    if(d>max){
        max=d;
    }
    height(root->left,++d);
    //here actually ++d and then --d thats why i have used d in next step
    // --d to go up ++d to go right
    height(root->right,d);
    --d;
     
     
     
}
int main(){
    root = newnode(1);
    root->left = newnode(5);
    root->right = newnode(8);
    root->left->left = newnode(2);
    root->left->right = newnode(4);
    root->right->left = newnode(9);
    root->right->right = newnode(10);
    root->right->right->right= newnode(13);
  
    height(root,0);
    printf("\nHeight: %d",max);
    return 0;

}

Output

Node:1,Height: 0
Node:5,Height: 1
Node:2,Height: 2
Node:4,Height: 2
Node:8,Height: 1
Node:9,Height: 2
Node:10,Height: 2
Node:13,Height: 3

Height: 3


RUN THIS

0 comments:

Post a Comment