class Node {
int val;
Node left, right;
Node(int val) { this.val = val; left = right = null; }
}
public class WhyTreesExist {
// Search in array
static boolean searchArray(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) return true; // found target
}
return false; // not found
}
// Search in linked list
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; next = null; }
}
static boolean searchLinkedList(ListNode head, int target) {
ListNode curr = head;
while (curr != null) {
if (curr.val == target) return true; // found target
curr = curr.next; // move to next node
}
return false; // not found
}
// Search in binary tree
static boolean searchTree(Node root, int target) {
if (root == null) return false; // base case
if (root.val == target) return true; // found target
// search left subtree
if (searchTree(root.left, target)) return true;
// search right subtree
return searchTree(root.right, target);
}
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
ListNode head = new ListNode(10);
head.next = new ListNode(20);
head.next.next = new ListNode(30);
head.next.next.next = new ListNode(40);
head.next.next.next.next = new ListNode(50);
Node root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
System.out.println("Search 50 in array: " + searchArray(arr, 50));
System.out.println("Search 50 in linked list: " + searchLinkedList(head, 50));
System.out.println("Search 50 in tree: " + searchTree(root, 50));
}
}if (arr[i] == target) return true; // found target
check each array element for target
while (curr != null) { if (curr.val == target) return true; curr = curr.next; }
traverse linked list nodes until target found or end
if (root == null) return false; if (root.val == target) return true;
base case and check current tree node for target
if (searchTree(root.left, target)) return true; return searchTree(root.right, target);
recursively search left then right subtree
Search 50 in array: true
Search 50 in linked list: true
Search 50 in tree: true