1. Full Tree DFS (Unordered Search)
Intuition
Visit every node in the tree using recursion. Check if (root.val == val) return root. Otherwise search left and search right. Takes O(N) time and O(H) stack space.
When to apply: Baseline comparison for generic binary trees.
Algorithm
- Traverse every node in the tree using DFS and return the matching node without using BST ordering.
#include <iostream> struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}}; class Solution {public: TreeNode* searchBST(TreeNode* root, int val) { if (!root) return nullptr; if (root->val == val) return root; TreeNode* left = searchBST(root->left, val); if (left) return left; return searchBST(root->right, val); }}; int main() { TreeNode* root = new TreeNode(4); root->left = new TreeNode(2); root->right = new TreeNode(7); root->left->left = new TreeNode(1); root->left->right = new TreeNode(3); Solution sol; TreeNode* res = sol.searchBST(root, 2); std::cout << "Found: " << (res ? res->val : -1) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) - Space complexity:
O(H) recursion stack space