Skip to content

Commit c291830

Browse files
authored
Create Search in BST
1 parent 9e292e1 commit c291830

File tree

1 file changed

+60
-0
lines changed
  • Course 2 - Data Structures in JAVA/Lecture 13 - BST I

1 file changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
Given a BST and an integer k. Find if the integer k is present in given BST or not. You have to return true, if node with data k is present, return false otherwise.
3+
Note: Assume that BST contains all unique elements.
4+
5+
Input Format:
6+
The first line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is separated by space. If any node does not have left or right child, take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, it will not be a part of the data of any node.
7+
The following line of input contains an integer, that denotes the value of k.
8+
9+
Output Format:
10+
The first and only line of output contains a boolean value. Print true, if node with data k is present, print false otherwise.
11+
12+
Constraints:
13+
Time Limit: 1 second
14+
15+
Sample Input 1 :
16+
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
17+
2
18+
Sample Output 1 :
19+
true
20+
S
21+
ample Input 2 :
22+
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
23+
12
24+
Sample Output 2 :
25+
false
26+
*/
27+
public class Solution {
28+
29+
/*
30+
* Binary Tree Node class
31+
*
32+
* class BinaryTreeNode<T> { T data; BinaryTreeNode<T> left; BinaryTreeNode<T> right;
33+
*
34+
* public BinaryTreeNode(T data) { this.data = data; } }
35+
*/
36+
37+
38+
public static boolean searchInBST(BinaryTreeNode<Integer> root, int k) {
39+
if (root==null)
40+
{
41+
return false;
42+
}
43+
44+
int rootData=root.data;
45+
if (k<rootData)
46+
{
47+
return searchInBST(root.left,k);
48+
}
49+
else if(k>rootData)
50+
{
51+
return searchInBST(root.right,k);
52+
}
53+
else
54+
{
55+
return true;
56+
}
57+
58+
59+
}
60+
}

0 commit comments

Comments
 (0)