#include <iostream>
#include <vector>
using namespace std;
// Node for linked list
struct ListNode {
int val;
ListNode* next;
ListNode(int v) : val(v), next(nullptr) {}
};
// Node for tree
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}
};
// Search in linked list
bool searchList(ListNode* head, int target) {
while (head != nullptr) {
if (head->val == target) return true; // found target
head = head->next; // move to next node
}
return false; // not found
}
// Search in array
bool searchArray(const vector<int>& arr, int target) {
for (int val : arr) {
if (val == target) return true; // found target
}
return false; // not found
}
// Search in binary tree
bool searchTree(TreeNode* root, int target) {
if (root == nullptr) return false; // base case: empty node
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);
}
int main() {
// Create linked list 1->2->3->4->5
ListNode* 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);
// Create array [1,2,3,4,5]
vector<int> arr = {1, 2, 3, 4, 5};
// Create tree:
// 1
// / \
// 2 3
// / \
// 4 5
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
int target = 5;
cout << "Search in linked list: " << (searchList(head, target) ? "Found" : "Not Found") << endl;
cout << "Search in array: " << (searchArray(arr, target) ? "Found" : "Not Found") << endl;
cout << "Search in tree: " << (searchTree(root, target) ? "Found" : "Not Found") << endl;
return 0;
}while (head != nullptr) {
traverse linked list nodes one by one
if (head->val == target) return true;
check if current node has target value
iterate array elements one by one
if (val == target) return true;
check if current array element matches target
if (root == nullptr) return false;
base case: empty tree node means target not found here
if (root->val == target) return true;
check if current tree node has target value
if (searchTree(root->left, target)) return true;
search left subtree recursively
return searchTree(root->right, target);
search right subtree recursively if not found left
Search in linked list: Found
Search in array: Found
Search in tree: Found