Open In App

Search a node in Binary Tree

Last Updated : 21 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary tree and a key. The task is to search and check if the given key exists in the binary tree or not.

Examples:

Input:

search-a-node-in-binary-tree


Output: True

Input:

search-a-node-in-binary-tree-2

Output: False

Approach:

The idea is to use any of the tree traversals to traverse the tree and while traversing check if the current node matches with the given node, return true if any node matches with the given node and stop traversing further and if the tree is completely traversed and none of the node matches with the given node then return False.

Below is the implementation of the above approach: 

C++
// C++ program to check if a node exists
// in a binary tree
#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
    Node(int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Function to traverse the tree in preorder
// and check if the given node exists in it
bool ifNodeExists(Node* root, int key) {
    if (root == nullptr)
        return false;

    if (root->data == key)
        return true;

    // then recur on left subtree
    bool res1 = ifNodeExists(root->left, key);
    
    // node found, no need to look further
    if (res1) return true; 

    // node is not found in left, 
    // so recur on right subtree
    bool res2 = ifNodeExists(root->right, key);

    return res2;
}

int main() {
   
    // Binary tree  
    //          0
    //        /  \
    //       1    2
    //      / \   / \
    //     3   4 5   6
    //    /   / \
    //   7   8   9
    Node* root = new Node(0);
    root->left = new Node(1);
    root->left->left = new Node(3);
    root->left->left->left = new Node(7);
    root->left->right = new Node(4);
    root->left->right->left = new Node(8);
    root->left->right->right = new Node(9);
    root->right = new Node(2);
    root->right->left = new Node(5);
    root->right->right = new Node(6);

    int key = 4;

    if (ifNodeExists(root, key))
        cout << "True";
    else
        cout << "False";

    return 0;
}
C
// C program to check if a node exists
// in a binary tree
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *left, *right;
};

// Function to traverse the tree in preorder
// and check if the given node exists in it
int ifNodeExists(struct Node* root, int key) {
    if (root == NULL)
        return 0;

    if (root->data == key)
        return 1;

    // then recur on left subtree
    int res1 = ifNodeExists(root->left, key);

    // node found, no need to look further
    if (res1) return 1;

    // node is not found in left, 
    // so recur on right subtree
    int res2 = ifNodeExists(root->right, key);

    return res2;
}

struct Node* createNode(int x) {
    struct Node* newNode = 
    	(struct Node*)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

int main() {
    
    // Binary tree  
    //          0
    //        /  \
    //       1    2
    //      / \   / \
    //     3   4 5   6
    //    /   / \
    //   7   8   9
    struct Node* root = createNode(0);
    root->left = createNode(1);
    root->left->left = createNode(3);
    root->left->left->left = createNode(7);
    root->left->right = createNode(4);
    root->left->right->left = createNode(8);
    root->left->right->right = createNode(9);
    root->right = createNode(2);
    root->right->left = createNode(5);
    root->right->right = createNode(6);

    int key = 4;

    if (ifNodeExists(root, key))
        printf("True");
    else
        printf("False");

    return 0;
}
Java
// Java program to check if a node exists
// in a binary tree

class Node {
    int data;
    Node left, right;
    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to traverse the tree in preorder
    // and check if the given node exists in it
    static boolean ifNodeExists(Node root, int key) {
        if (root == null)
            return false;

        if (root.data == key)
            return true;

        // then recur on left subtree
        boolean res1 = ifNodeExists(root.left, key);

        // node found, no need to look further
        if (res1) return true;

        // node is not found in left,
        // so recur on right subtree
        boolean res2 = ifNodeExists(root.right, key);

        return res2;
    }

    public static void main(String[] args) {

        // Binary tree
        //          0
        //        /  \
        //       1    2
        //      / \   / \
        //     3   4 5   6
        //    /   / \
        //   7   8   9
        Node root = new Node(0);
        root.left = new Node(1);
        root.left.left = new Node(3);
        root.left.left.left = new Node(7);
        root.left.right = new Node(4);
        root.left.right.left = new Node(8);
        root.left.right.right = new Node(9);
        root.right = new Node(2);
        root.right.left = new Node(5);
        root.right.right = new Node(6);

        int key = 4;

        if (ifNodeExists(root, key))
            System.out.println("True");
        else
            System.out.println("False");
    }
}
Python
# Python program to check if a node exists
# in a binary tree

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function to traverse the tree in preorder
# and check if the given node exists in it
def ifNodeExists(root, key):
    if root is None:
        return False

    if root.data == key:
        return True

    # then recur on left subtree
    res1 = ifNodeExists(root.left, key)

    # node found, no need to look further
    if res1:
        return True

    # node is not found in left,
    # so recur on right subtree
    res2 = ifNodeExists(root.right, key)

    return res2

if __name__ == "__main__":
    
    # Binary tree  
    #          0
    #        /  \
    #       1    2
    #      / \   / \
    #     3   4 5   6
    #    /   / \
    #   7   8   9
    root = Node(0)
    root.left = Node(1)
    root.left.left = Node(3)
    root.left.left.left = Node(7)
    root.left.right = Node(4)
    root.left.right.left = Node(8)
    root.left.right.right = Node(9)
    root.right = Node(2)
    root.right.left = Node(5)
    root.right.right = Node(6)

    key = 4

    if ifNodeExists(root, key):
        print("True")
    else:
        print("False")
C#
// C# program to check if a node exists
// in a binary tree

class Node {
    public int data;
    public Node left, right;
    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to traverse the tree in preorder
    // and check if the given node exists in it
    static bool ifNodeExists(Node root, int key) {
        if (root == null)
            return false;

        if (root.data == key)
            return true;

        // then recur on left subtree
        bool res1 = ifNodeExists(root.left, key);

        // node found, no need to look further
        if (res1) return true;

        // node is not found in left,
        // so recur on right subtree
        bool res2 = ifNodeExists(root.right, key);

        return res2;
    }

    static void Main(string[] args) {

        // Binary tree
        //          0
        //        /  \
        //       1    2
        //      / \   / \
        //     3   4 5   6
        //    /   / \
        //   7   8   9
        Node root = new Node(0);
        root.left = new Node(1);
        root.left.left = new Node(3);
        root.left.left.left = new Node(7);
        root.left.right = new Node(4);
        root.left.right.left = new Node(8);
        root.left.right.right = new Node(9);
        root.right = new Node(2);
        root.right.left = new Node(5);
        root.right.right = new Node(6);

        int key = 4;

        if (ifNodeExists(root, key))
            System.Console.WriteLine("True");
        else
            System.Console.WriteLine("False");
    }
}
JavaScript
// JavaScript program to check if a node exists
// in a binary tree

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function to traverse the tree in preorder
// and check if the given node exists in it
function ifNodeExists(root, key) {
    if (root === null)
        return false;

    if (root.data === key)
        return true;

    // then recur on left subtree
    let res1 = ifNodeExists(root.left, key);

    // node found, no need to look further
    if (res1) return true;

    // node is not found in left,
    // so recur on right subtree
    let res2 = ifNodeExists(root.right, key);

    return res2;
}

// Binary tree
//          0
//        /  \
//       1    2
//      / \   / \
//     3   4 5   6
//    /   / \
//   7   8   9
let root = new Node(0);
root.left = new Node(1);
root.left.left = new Node(3);
root.left.left.left = new Node(7);
root.left.right = new Node(4);
root.left.right.left = new Node(8);
root.left.right.right = new Node(9);
root.right = new Node(2);
root.right.left = new Node(5);
root.right.right = new Node(6);

let key = 4;

if (ifNodeExists(root, key))
    console.log("True");
else
    console.log("False");

Output
True

Time Complexity: O(n), where n is the number of nodes in the tree.
Auxiliary Space: O(h), where h is the height of the tree.


Next Article
Practice Tags :

Similar Reads