DEV Community

Mujahida Joynab
Mujahida Joynab

Posted on

Searching in BST

We will go to the left side if the value is less than the root node . If the value is greater than the left node then we will go to the right of the node .

#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
    int val;
    Node *right;
    Node *left;
    Node(int value)
    {
        this->val = value;
        this->right = NULL;
        this->left = NULL;
    }
};

Node *input_tree()
{

    Node *root;
    int val;
    cin >> val;
    if (val == -1)
        return NULL;
    else
        root = new Node(val);

    queue<Node *> q;
    if (root)
        q.push(root);

    while (!q.empty())
    {

        Node *p = q.front();
        q.pop();

        int l, r;
        cin >> l >> r;
        Node *myLeft, *myRight;

        if (l == -1)
        {
            myLeft = NULL;
        }
        else
            myLeft = new Node(l);
        if (r == -1)
        {
            myRight = NULL;
        }
        else
            myRight = new Node(r);
        p->left = myLeft;
        p->right = myRight;

        if (p->left)
            q.push(p->left);
        if (p->right)
            q.push(p->right);
    }
    return root;
}

bool search(Node *root, int val)
{
    if (root == NULL)
        return false;

    if (root->val == val)
    {
        return true;
    }
    else if (val < root->val)

        return search(root->left, val);

    else

        return search(root->right, val);
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    Node *root = input_tree();

    int val;
    cin >> val;

    if (search(root, val))
        cout << "Found\n";
    else
        cout << "Not found\n";
}
Enter fullscreen mode Exit fullscreen mode

Complexity

TC of Binary search is log(N)
But in Binary Search Tree the order of time can not be half all time . Because the size may not become half always .
Best Test Case
O(longN)

Worst Test Case - When the value is not in the binary Search Tree .
The time complexity is O(N) .

So the time complexity is until Binary tree height .

Time Complexity is - O(Height) / O(H) .

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay