-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchGivenKeyInBSTIterative.java
80 lines (67 loc) · 1.94 KB
/
SearchGivenKeyInBSTIterative.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package Practice;
/**
* SearchGivenKeyInBSTIterative
*/
public class SearchGivenKeyInBSTIterative {
class Node{
int data;
Node left, right;
Node(int data){
this.data = data;
this.left = this.right = null;
}
}
static Node insert(Node root, int val){
if(root == null){
return (new SearchGivenKeyInBSTIterative()).new Node(val);
}
if(root.data > val){
root.left = insert(root.left, val);
}
if(root.data < val){
root.right = insert(root.right, val);
}
return root;
}
static void inorder(Node root){
if(root == null)
return;
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
static void search(Node root, int key){
Node curr= root, parent= null;
while(curr != null && curr.data != key){
parent = curr;
if(key < curr.data){
curr = curr.left;
}else{
curr = curr.right;
}
}
if(curr == null){
System.out.println("Key not found");
return;
}
if(parent == null && curr.data == key){
System.out.println("The Key is the root node of the BST.");
}
else if(key < parent.data){
System.out.println("The key " + key + " is the left child of " + parent.data);
}else{
System.out.println("The key " + key + " is the right child of " + parent.data);
}
}
public static void main(String[] args) {
Node root = null;
int[] keys = new int[]{ 15, 10, 20, 8, 12, 16, 25 };
for(int key:keys){
root = insert(root, key);
}
System.out.println("input inorder:" );
inorder(root);
System.out.println("\noutput:");
search(root, 100);
}
}