Binary Search Tree(create,order)
#include<iostream> #include<stdlib.h> using namespace std; typedef struct node{ int data; struct node* left; struct node* right; }Node; typedef struct tree{ Node *root; }Tree; void insert(Tree *tree,int value){ Node* node=(Node *)malloc(sizeof(Node)); node->data=value; node->left=NULL; node->right=NULL; if(tree->root == NULL){ tree->root=node; } else{ Node *temp=tree->root; while(temp != NULL){ if(value <temp->data){ if(temp->left == NULL){ temp->left=node; return; }else{ temp=temp->left; } }else{ if(temp->right == NULL){ temp->right=node; return; }else{ temp=temp->right; } } } } } void preorder(Node * node){ if(node !=NULL){ cout<<node->data<<endl; preorder(node->left); preorder(node->right); } } void inorder(Node* node){ if(node!=NULL){ inorder(node->left); cout<<node->data<<endl; inorder(node->right); } } void postorder(Node* node){ if(node != NULL){ postorder(node->left); postorder(node->right); cout<<node->data<<endl; } } int get_height(Node* node){ if(node == NULL){ return 0; }else{ int left_height=get_height(node->left); int right_height=get_height(node->right); int max=left_height; if(right_height>max){ max=right_height; } return max+1; } } int get_maximum(Node *node){ if(node == NULL){ return -1; } else{ int m1=get_maximum(node->left); int m2=get_maximum(node->right); int m3=node->data; int max=m1; if(m2>max){ max=m2; } if(m3>max){ max=m3; } return max; } } int main(){ int array[7]={6,3,8,2,5,1,7}; Tree tree; tree.root=NULL; for(int i=0;i<7;i++){ insert(&tree,array[i]); } inorder(tree.root); cout<<"The depth is:"<<get_height(tree.root)<<endl; cout<<"The maximum is:"<<get_maximum(tree.root); return 0; }