Java Solution:
public class SearchInBST {
public static void main(String[] args) {
Node root = new Node(5);
Node node2 = new Node(2);
Node node3 = new Node(7);
root.left = node2;
root.right = node3;
Node node4 = new Node(1);
Node node5 = new Node(3);
node2.left = node4;
node2.right = node5;
Node node6 = new Node(6);
Node node7 = new Node(8);
node3.left = node6;
node3.right = node7;
Node foundElement = find(root, 3);
if(foundElement != null){
System.out.println("Element found");
}else {
System.out.println("Element not found");
}
System.out.println();
}
private static Node find(Node root, int key){
if(root == null){
return root;
}
if(root.data == key){
return root;
}else if(key < root.data){
return find(root.left, key);
}else {
return find(root.right, key);
}
}
static class Node {
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
}
}
}
No comments:
Post a Comment