The Wayback Machine - https://web.archive.org/web/20241126224206/https://www.geeksforgeeks.org/search-a-node-in-binary-tree/
Open In App

Search a node in Binary Tree

Last Updated : 21 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Previous Article
Next Article

Similar Reads

Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
Difference between Binary Tree and Binary Search Tree
Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children. Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, wi
2 min read
Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree. Examples Input: Output: Explanation: The above Binary tree is converted to Binary Search tree by keeping the original structure of Binary Tree. Approach: The idea to recursively trav
7 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree. Example: Input: Output: Explanation: The above Binary tree is converted to Binary Search tree by keeping the original structure of Binary Tree. Approach: The idea is to recursively t
7 min read
Minimum swap required to convert binary tree to binary search tree
Given an array arr[] which represents a Complete Binary Tree i.e., if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swaps required to convert it into a Binary Search Tree. Examples: Input: arr[] = [5, 6, 7, 8, 9, 10, 11]Output: 3Explanation:Binary tree of the g
9 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
Given a Binary Search Tree and a binary integer K, the task is to convert Binary search tree into a Skewed Tree in increasing order if K = 0 or in decreasing order if K = 1. Examples: Input: K = 0, 5 / \ 3 6 Output: 3 \ 5 \ 6 Input: K = 1, 2 / \ 1 3 Output: 3 \ 2 \ 1 Approach: The key observation in the problem is that the first node of the skewed
10 min read
Flatten a Binary Search Tree to convert the tree into a wave list in place only
Given a Binary Search Tree consisting of N distinct nodes, the task is to flatten the given Binary Search Tree to convert the tree into a wave list. A wave list arr[0..n-1] is called a wave list if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= ... . Examples: Input: 1 / \ 0 10Output: 0 \ 10 \ 1 Input: 3 / \ 1 7 / \ / \ 0 2 5 10 O
12 min read
Find the minimum Sub-tree with target sum in a Binary search tree
Given a binary tree and a target, find the number of nodes in the minimum sub-tree with the given sum equal to the target which is also a binary search tree. Examples: Input: 13 / \ 5 23 / \ / \ N 17 N N / 16Target: 38Output: 3Explanation: 5, 17, 16 is the smallest subtree with length 3. Input: 7 / \ N 23 / \ 10 23 / \ / \ N 17 N NTarget: 73Output:
9 min read
Difference between Binary Search Tree and AVL Tree
Binary Search Tree:A binary Search Tree is a node-based binary tree data structure that has the following properties: The left subtree of a node contains only nodes with keys lesser than the node’s key.The right subtree of a node contains only nodes with keys greater than the node’s key.The left and right subtree each must also be a binary search t
2 min read
Postorder predecessor of a Node in Binary Search Tree
Given a binary tree and a node in the binary tree, find the Postorder predecessor of the given node. Examples: Consider the following binary tree 20 / \ 10 26 / \ / \ 4 18 24 27 / \ 14 19 / \ 13 15 Input : 4 Output : 10 Postorder traversal of given tree is 4, 13, 15, 14, 19, 18, 10, 24, 27, 26, 20. Input : 24 Output : 10 A simple solution is to fir
8 min read
How to insert a node in Binary Search Tree using Iteration
You are given a binary search tree (BST) and a value to insert into the tree. Print inorder traversal of the BST after the insertion.Example: Input:To the given BST insert 40 Output: Explanation:The new node 40 is a leaf node. Start searching from the root till a leaf node is hit, i.e while searching if a new value is greater than current node move
10 min read
Find the node with maximum value in a Binary Search Tree using recursion
Given a Binary Search Tree, the task is to find the node with maximum value. Examples: Input: Output: 22 Approach: Just traverse the node from root to right recursively until right is NULL. The node whose right is NULL is the node with the maximum value. Below is the implementation of the above approach: C/C++ Code // C++ implementation of the appr
7 min read
Traversal of Binary Search Tree in downward direction from a specific node
Given a Binary Search Tree with unique node values and a target value. Find the node whose data is equal to the target and return all the descendant (of the target) node's data which are vertically below the target node. Initially, you are at the root node. Note: If the target node is not present in bst then return -1. And, if No descendant node is
10 min read
Find the node with maximum value in a Binary Search Tree
Given a Binary Search Tree, the task is to find the node with the maximum value in a BST. For the above tree, we start with 20, then we move right to 22. We keep on moving to the right until we see NULL. Since the right of 22 is NULL, 22 is the node with the maximum value. Approach: This is quite simple. Just traverse the node from root to right re
15 min read
Find the node with minimum value in a Binary Search Tree
Given the root of a Binary Search Tree. The task is to find the minimum valued element in this given BST. Example: Input: Output: 1Explanation: The minimum element in the given BST is 1. Input: Output: 2Explanation: The minimum element in the given BST is 2 Table of Content [Naive Approach] Using Inorder Traversal - O(n) Time and O(n) Space[Expecte
12 min read
Find the node with minimum value in a Binary Search Tree using recursion
Given the root of a Binary Search Tree, the task is to find the minimum valued element in this given BST. Examples: Input: Output: 1Explanation: The minimum element in the given BST is 1. Input: Output: 2Explanation: The minimum element in the given BST is 2. Approach: The idea is to recursively traverse the Binary Search Tree (BST) starting from t
6 min read
Count the Number of Binary Search Trees present in a Binary Tree
Given a binary tree, the task is to count the number of Binary Search Trees present in it. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 4Here each leaf node represents a binary search tree and there are total 4 nodes. Input: 11 / \ 8 10 / / \ 5 9 8 / \ 4 6 Output: 6 Sub-tree rooted under node 5 is a BST 5 / \ 4 6 Another BST we have is rooted
10 min read
Convert a Generic Tree(N-array Tree) to Binary Tree
Prerequisite: Generic Trees(N-array Trees) In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree: The root of the Binary Tree is the Root of the Generic Tree.The left child of a node in the Generic Tree is the Left child of that node in the B
13 min read
Distance of each node of a Binary Tree from the root node using BFS
Given a Binary tree consisting of N nodes with values in the range [1, N], the task is to find the distance from the root node to every node of the tree. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 0 1 1 2 2 2 Explanation: The distance from the root to node 1 is 0. The distance from the root to node 2 is 1. The distance from the root to node 3 i
9 min read
Step by step Shortest Path from source node to destination node in a Binary Tree
Given a root of binary tree and two integers startValue and destValue denoting the starting and ending node respectively. The task is to find the shortest path from the start node to the end node and print the path in the form of directions given below. Going from one node to its left child node is indicated by the letter 'L'.Going from one node to
14 min read
Print Head node of every node in Binary Tree
Given the root of the Binary Tree. Print the parent node of each node in the given Binary Tree. Examples : Input: Binary Tree = {1, 2, 3, 4, 5, NULL, NULL, NULL, 6} Output : The Head Node of 6 is 4 The Head Nodeof 5 is 2The Head Node of 4 is 2The Head Node of 3 is 1 The Head Node of 2 is 1 Explanation: Clearly By Observing Image we are finding pare
7 min read
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. The following diagram sho
12 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Check whether a given binary tree is skewed binary tree or not?
Given a Binary Tree check whether it is skewed binary tree or not. A skewed tree is a tree where each node has only one child node or none. Examples: Input : 5 / 4 \ 3 / 2 Output : Yes Input : 5 / 4 \ 3 / \ 2 4 Output : No The idea is to check if a node has two children. If node has two children return false, else recursively compute whether subtre
13 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Check whether a binary tree is a full binary tree or not
A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here. For Example : Recommended PracticeFull binary treeTry It! To check whether a binary tree is a full binary tre
14 min read
Check if a binary tree is subtree of another binary tree | Set 2
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.For example, in the following case, Tree1 i
15+ min read
Practice Tags :
three90RightbarBannerImg