Skip to content

Instantly share code, notes, and snippets.

@baoqger
Created August 12, 2020 13:57
Show Gist options
  • Save baoqger/cad456ccbc9cf35d1ab76583e95f1751 to your computer and use it in GitHub Desktop.
Save baoqger/cad456ccbc9cf35d1ab76583e95f1751 to your computer and use it in GitHub Desktop.
binary tree in cpp
/*
LAB 3
Objectives 3
Binary tree's are data structures that have a hierarchical form and represent trees
whose elements have a maximum number of two children. These children are called the
left and the right child. The binary tree root represents the top node.
A node that has at least one child is considered a parent of its child.
A leaf is a node that has no children.
*/
#include <iostream>
class binary_tree{
private:
struct node{
int data;
node *left;
node *right;
node(int initdata, node *leftN, node *rightN): left(leftN), right(rightN), data(initdata) {}
~node(){
if (left!=nullptr)
delete left;
if (right!=nullptr)
delete right;
}
};
//attribute section
node *root;
//function section
void add(int newdata, node *ptr);
bool search(int targetdata, node *ptr);
public:
binary_tree(int rootdata){
binary_tree::root = new node(rootdata, nullptr, nullptr);
}
~binary_tree() {
delete binary_tree::root;
}
void addData(int inputdata){
binary_tree::add(inputdata, root);
}
bool searchItem(int item) {
return binary_tree::search(item, binary_tree::root);
}
int getroot(){
return root->data;
}
};
bool binary_tree::search(int targetdata, node *ptr){
if (ptr != nullptr && ptr->right ==nullptr && ptr->left==nullptr){
if (targetdata == ptr->data){
return true;
}else{
return false;
}
}
if (targetdata == ptr->data){
return true;
}else{
//not found
//searching to right
if (targetdata > ptr->data && ptr->right !=nullptr){
search(targetdata, ptr->right);
}else if(targetdata < ptr->data && ptr->left !=nullptr){
search(targetdata, ptr->left);
}
}
}
void binary_tree::add(int newdata, node *ptr){
//right
if (newdata > ptr->data){
if(ptr->right == nullptr){
ptr->right = new node(newdata,nullptr,nullptr);
}else{
binary_tree::add(newdata,ptr->right);
}
}else{
if(ptr->left == nullptr){
ptr->left = new node(newdata,nullptr,nullptr);
}else{
add(newdata,ptr->left);
}
}
}
int main() {
binary_tree tree(2);
tree.addData(10);
tree.addData(1);
tree.addData(20);
tree.addData(0);
std::cout<<tree.searchItem(0)<<std::endl;
std::cout<<tree.searchItem(9)<<std::endl;
tree.addData(11);
std::cout<<tree.searchItem(11)<<std::endl;
/* OUTPUT:
1
0
1
*/
std::cout<<tree.getroot()<<std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment