-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBinarySearchTree.java
39 lines (34 loc) · 1013 Bytes
/
BinarySearchTree.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
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
}
}
public class BinaryTreeSearch {
public static boolean binarySearch(TreeNode root, int target) {
while (root != null) {
if (target == root.val) {
return true;
} else if (target < root.val) {
root = root.left;
} else {
root = root.right;
}
}
return false;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(10);
root.left = new TreeNode(5);
root.right = new TreeNode(15);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(7);
int target = 7;
boolean found = binarySearch(root, target);
System.out.println("Value " + target + " found: " + found);
}
}