-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchInBST.java
More file actions
31 lines (29 loc) · 797 Bytes
/
SearchInBST.java
File metadata and controls
31 lines (29 loc) · 797 Bytes
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
public class SearchInBST {
public static void main(String[] args) {
TreeNode root=new TreeNode(4);
root.left=new TreeNode(2);
root.right=new TreeNode(7);
root.left.left=new TreeNode(1);
root.left.right=new TreeNode(3);
SearchInBST o=new SearchInBST();
System.out.println(o.searchBST(root,2));
}
public TreeNode searchBST(TreeNode root, int val) {
while(root!=null && root.data != val){
if(root.data<val){
root=root.right;
}else{
root=root.left;
}
}
return root;
}
}
class TreeNode{
int data;
TreeNode left,right;
public TreeNode(int key){
key=data;
left=right=null;
}
}