class TreeNode {
value: string;
left: TreeNode | null;
right: TreeNode | null;
constructor(value: string) {
this.value = value;
this.left = null;
this.right = null;
}
}
function searchArray(arr: string[], target: string): boolean {
for (const item of arr) {
if (item === target) return true;
}
return false;
}
class ListNode {
value: string;
next: ListNode | null;
constructor(value: string) {
this.value = value;
this.next = null;
}
}
function searchLinkedList(head: ListNode | null, target: string): boolean {
let current = head;
while (current !== null) {
if (current.value === target) return true;
current = current.next;
}
return false;
}
function searchTree(root: TreeNode | null, target: string): boolean {
if (root === null) return false;
if (root.value === target) return true;
return searchTree(root.left, target) || searchTree(root.right, target);
}
// Driver code
const arr = ["Alice", "Bob", "Carol", "Dave", "Eve", "Frank", "Grace"];
const head = new ListNode("Alice");
head.next = new ListNode("Bob");
head.next.next = new ListNode("Carol");
head.next.next.next = new ListNode("Dave");
head.next.next.next.next = new ListNode("Eve");
head.next.next.next.next.next = new ListNode("Frank");
head.next.next.next.next.next.next = new ListNode("Grace");
const root = new TreeNode("Root");
root.left = new TreeNode("A");
root.right = new TreeNode("B");
root.left.left = new TreeNode("C");
root.left.right = new TreeNode("D");
root.right.left = new TreeNode("Eve");
root.right.right = new TreeNode("F");
console.log("Search 'Eve' in array:", searchArray(arr, "Eve"));
console.log("Search 'Eve' in linked list:", searchLinkedList(head, "Eve"));
console.log("Search 'Eve' in tree:", searchTree(root, "Eve"));for (const item of arr) { if (item === target) return true; }
Check each array element one by one until target found
while (current !== null) { if (current.value === target) return true; current = current.next; }
Traverse linked list nodes sequentially until target found
if (root === null) return false; if (root.value === target) return true; return searchTree(root.left, target) || searchTree(root.right, target);
Recursively check tree nodes, branching left and right to find target
Search 'Eve' in array: true
Search 'Eve' in linked list: true
Search 'Eve' in tree: true