Answer to Question #266846 in C++ for Abhi

Question #266846

Write a program to implement binary search on 5 elements.


1
Expert's answer
2021-11-16T18:37:17-0500
#include <iostream>
using namespace std;
 
class SearchTree
{
    int item;
    SearchTree *leftNode;
	SearchTree *rightNode;
 
public:
    
    SearchTree();
 
    
    SearchTree(int);
 
    
    SearchTree* Insert(SearchTree*, int);
 
    
    void Inorder(SearchTree*);
};
 
SearchTree ::SearchTree()
    : item(0)
    , leftNode(NULL)
    , rightNode(NULL)
{
}
 


SearchTree ::SearchTree(int value)
{
    item = value;
    leftNode = rightNode = NULL;
}
 


SearchTree* SearchTree ::Insert(SearchTree* node, int value)
{
    if (!node)
    {
        
        return new SearchTree(value);
    }
 
    
    if (value > node->item)
    {
        
        node->rightNode = Insert(node->rightNode, value);
    }
    else
    {
        
        node->leftNode = Insert(node->leftNode, value);
    }
 
    
    return node;
}
 
void SearchTree ::Inorder(SearchTree* node)
{
    if (!node) {
        return;
    }
    Inorder(node->leftNode);
    cout << node->item << "  ";
    Inorder(node->rightNode);
}
 


int main()
{
    SearchTree binary, *node = NULL;
    node = binary.Insert(node, 5);
    binary.Insert(node, 3);
    binary.Insert(node, 2);
    binary.Insert(node, 4);
    binary.Insert(node, 7);
    binary.Insert(node, 6);
    binary.Insert(node, 8);
 
    binary.Inorder(node);
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS