Implement searching algorithm in binary search tree in C++

Code

// Implement searching algorithm in binary search tree

#include <iostream>

using namespace std;

class Node {
public:
int data;
Node *left;
Node *right;
};

Node *newNode(int data) {
Node *node = new Node();
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}

Node *insert(Node *node, int data) {
if (node == NULL) {
return newNode(data);
}
if (data < node->data) {
node->left = insert(node->left, data);
} else if (data > node->data) {
node->right = insert(node->right, data);
}
return node;
}

bool search(Node *root, int data) {
if (root == NULL) {
return false;
}
if (root->data == data) {
return true;
}
if (data < root->data) {
return search(root->left, data);
} else {
return search(root->right, data);
}
}

int main() {
Node *root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
if (search(root, 80)) {
cout << "Node found" << endl;
} else {
cout << "Node not found" << endl;
}
return 0;
}


Output

Run the code... enjoy