class TreeNode {
constructor(value) {
this.value = value;
this.children = [];
}
addChild(node) {
this.children.push(node);
}
}
// Search in array
function searchArray(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return true;
}
return false;
}
// Search in linked list
class ListNode {
constructor(value) {
this.value = value;
this.next = null;
}
}
function searchLinkedList(head, target) {
let curr = head;
while (curr !== null) {
if (curr.value === target) return true;
curr = curr.next;
}
return false;
}
// Search in tree
function searchTree(root, target) {
if (root === null) return false;
if (root.value === target) return true;
for (const child of root.children) {
if (searchTree(child, target)) return true;
}
return false;
}
// Driver code
const arr = [1, 2, 3, 4, 5];
const head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
const root = new TreeNode(1);
const node2 = new TreeNode(2);
const node3 = new TreeNode(3);
const node4 = new TreeNode(4);
const node5 = new TreeNode(5);
const node6 = new TreeNode(6);
root.addChild(node2);
root.addChild(node3);
node2.addChild(node4);
node2.addChild(node5);
node3.addChild(node6);
console.log("Search 5 in array:", searchArray(arr, 5));
console.log("Search 5 in linked list:", searchLinkedList(head, 5));
console.log("Search 5 in tree:", searchTree(root, 5));
// Add new node 7 to tree
const node7 = new TreeNode(7);
node3.addChild(node7);
// Print tree structure simple
function printTree(node, prefix = "") {
console.log(prefix + node.value);
for (const child of node.children) {
printTree(child, prefix + " ");
}
}
console.log("Tree structure after adding 7:");
printTree(root);for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return true;
}
Check each array element one by one to find target
while (curr !== null) {
if (curr.value === target) return true;
curr = curr.next;
}
Traverse linked list nodes sequentially to find target
if (root === null) return false;
if (root.value === target) return true;
for (const child of root.children) {
if (searchTree(child, target)) return true;
}
Recursively check tree nodes and their children for target
Add new child node to tree without shifting other nodes
Search 5 in array: true
Search 5 in linked list: true
Search 5 in tree: true
Tree structure after adding 7:
1
2
4
5
3
6
7