Binary tree is a famous data structure widely used in problem solving and i will show class include insert function and calculate max depth of tree
#include<iostream>
#include<stdio.h>
using namespace std;
class Node
{
public:
int data;
Node* left;
Node*right;
Node(int i)
{
data = i ;
right = NULL;
left = NULL;
}
};
class NodeOperation
{
Node* insert(Node*root,int data)
{
if (root==NULL)
{
return new Node(data);
}
Node * cur ;
if(data>=root->right)
{
cur = insert(root->right,data);
root->right = cur;
}
else
{
cur = insert(root->left,data);
root->left = cur;
}
}
int calc_height(Node*root)
{
if(root==NULL)
{
return 0;
}
if(root->right==NULL && root->left)
{
return 0;
}
int rdepth = calc_height(root->right);
int ldepth = calc_height(root->left);
if(rdepth>ldepth)
return rdepth+1;
return ldepth+1;
}
};
int main()
{
NodeOperation oper;
cout<<"enter node num :";
int num = 0;
cin>>num;
Node *root = NULL;
while(num--)
{
root = oper.insert(root,num);
}
cout<<"height of tree"+calc_height(root);.
return 0;
}
No comments:
Post a Comment