Search a node in BST in java

Search a node in BST in java

You are given the root of a binary search tree (BST) and an integer val.

Find the node in the BST that the node’s value equals val and return true. If such a node does not exist, return false.

Input

The first line inputs N, the number of nodes and X, value of the node to find.
The second line inputs the value of N nodes of the BST.

Output

Print “YES” if node is present else “NO” in a new line.

Example 1

Input

7 87
2 81 42 87 90 42 45 66

Output

YES

Explaination

   2
    \
    81
   /  \
  42   87
 /  \   \
45  66   90

As 87 is present in the given nodes , so the output will be YES.

Example 2

Input

7 69
2 81 42 87 90 42 45 66

Output

NO

Explaination

   2
    \
    81
   /  \
  42   87
 /  \   \
45  66   90

As 69 is not present in the given nodes , so the output will be NO.

Constraints:

1 <= N <= 1000
-1000 <= val[node] <= 1000

Solution of Search a node in BST in java:–

import java.util.*;
import java.lang.*;
import java.io.*;

class Node{
  int val;
  Node left, right;
  Node(int val){
    this.val = val;
    left = null;
    right = null;
  }
}

class BST{
  Node root;
  BST(){
    root = null;
  }
  Node insert(Node node, int val){
    if(node == null){
      node = new Node(val);
      return node;
    }else if(val < node.val){
      node.left = insert(node.left, val);
    }else{
      node.right = insert(node.right, val);
    }
    return node;
  }
}

public class Main
{
    public static boolean find(Node node, int x){
        if(node == null)
            return false;
        if(node.val == x)return true;
        if(node.val > x)return find(node.left, x);
        else  return find(node.right, x);
    }
	public static void main (String[] args) throws java.lang.Exception
	{
      Scanner sc = new Scanner(System.in);
      int n = sc.nextInt();
      int x = sc.nextInt();
      BST tree = new BST();
      for(int i = 0; i < n; i++){
          tree.root = tree.insert(tree.root, sc.nextInt());
      }
      boolean ans = find(tree.root, x);
      if(ans)System.out.print("YES\n");
      else System.out.print("NO\n");
        }}

Add a Comment

Your email address will not be published. Required fields are marked *