Solved programming problem

Find Depth - Height of a Tree in C++.

Source code

#include <iostream>

using namespace std;

struct tree

{

    int data;

    struct tree *right,*left;

};

typedef struct tree node;

node *head =NULL;

node *insert_bst(node *&temp,int value) ///save the address in temp

{

    if(temp==NULL)

    {

        temp = new node();

        temp->data=value;

        temp->right=NULL;

        temp->left=NULL;

    }

    else if(temp->data <= value ) ///compare temp->data with value

    {

        insert_bst(temp->right,value); ///if the value is grater then temp->data

    }

    else

    {

         insert_bst(temp->left,value); ///if the value is smaller then temp->data

    }

}

void print(node *temp)

{

    if(temp==NULL)

    {

        return;

    }

    print(temp->left);

    cout<<temp->data<<" ";

    print(temp->right);

}

int max_find(int left, int right)

{

    if(left>right)

    {

        return left;

    }

    else return right;

}

int find_depth(node *root)

{

    if(root==NULL)

    {

        return 0;

    }

    int left = find_depth(root->left); ///find total number of node in left side

    int right= find_depth(root->right);///find total number of node in right side

    return max_find(left,right)+1; ///find the max between left right

}

int main()

{

    int flag=1,n,value;

    while(flag==1)

    {

        cout<<"Press 1 for Insert Data 0 to Exit: ";

         cin>>n;

         if(n!=1) break;

         cout<<"Value: ";

         cin>>value;

         insert_bst(head,value);

    }

    cout<<"Print Inorder: ";

    print(head);

    cout<<endl;

    cout<<"Hight: "<<find_depth(head)<<endl;

    return 0;

}

Output

Press 1 for Insert Data 0 to Exit: 1
Value: 1
Press 1 for Insert Data 0 to Exit: 1
Value: 3
Press 1 for Insert Data 0 to Exit: 1
Value: 2
Press 1 for Insert Data 0 to Exit: 1
Value: 3
Press 1 for Insert Data 0 to Exit: 1
Value: 3
Press 1 for Insert Data 0 to Exit: 0
Print Inorder: 1 2 3 3 3
Hight: 4

Join the discussion

Add your comment