Skip to content

Instantly share code, notes, and snippets.

@dumbbellcode
Last active May 16, 2019 05:28
Show Gist options
  • Save dumbbellcode/ae3fd026e80248e1ee11c56b0f743514 to your computer and use it in GitHub Desktop.
Save dumbbellcode/ae3fd026e80248e1ee11c56b0f743514 to your computer and use it in GitHub Desktop.
Binary tree (construction,find min element,find height,etc)
#include <iostream>
using namespace std;
struct node
{ int data; node*left ; node*right ;//data,left child pointer,right ch ptr.
};
node* makenode(int data)
{ //this function creates a new node pointer,makes that pointer point to a node,sets node values and returns that pointer.
node* x= new node();
x->left = NULL;
x->right=NULL;
x->data=data;
return x;
}
node* insert(node* root,int data)
{
if(root==NULL) { root = makenode(data); return root ;}
//since root in main is local variable it won't be modified,so we return this root value(which is address to a node in heap) and store it in the root of main function
else if(data<=root->data)
{ root->left=insert(root->left,data);
return root;
}
else
{ root->right=insert(root->right,data);// recursive call
return root; }
}
bool search(node* root,int data)
{
if(root==NULL){ return false;}
else if(root->data=data){ return true;}
else if(data>=root->data){ return search(root->left,data);}
else { return search(root->right,data);}
}
//minimum in a binarytree
int findmin(node* root)
{
if(root->left==NULL){ return root->data; }
else{
return findmin(root->left);
}
}
//height of a binary tree
int findheight(node* root)
{
if(root==NULL) { return -1;}
return max(findheight(root->left),findheight(root->right))+1;
}
int main()
{ node* root=NULL;
root = insert(root,20);
root = insert(root,15);
root = insert(root,25);
cout<<search(root,20);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment