forked from AkashMarkad/Hacktoberfest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Search in BST.java
47 lines (39 loc) · 1.18 KB
/
Search in BST.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Search in BST
// we know that the bst have the smaller elements on the left and greater elements on the right
// so if the key is grater than the root then we go on right else go on left if found return node
// code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
while(root != null && root.val != val){
root = (val < root.val) ? root.left : root.right;
}
return root;
}
}
// Coding Studio Solution :
public class Solution {
public static Boolean searchInBST(BinaryTreeNode<Integer> root, int x) {
// Write your code here.
if(root == null) return false;
while(root != null){
if(root.data == x) return true;
root = x<root.data ? root.left : root.right;
}
return false;
}
}