1. BST Binary Search for Complement (O(N * H))
Intuition
Traverse every node in the tree using DFS. For each visited node curr, execute a binary search in the BST starting from root to look for a node with value k - curr.val. Ensure the found node is not curr itself. Takes O(N * H) time and O(H) recursion stack space.
When to apply: Baseline comparison without auxiliary arrays or sets.
Algorithm
- For each node curr, search the BST for k - curr.val starting from root.
#include <iostream> struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}}; class Solution { bool search(TreeNode* root, TreeNode* curr, int val) { TreeNode* p = root; while (p) { if (p->val == val && p != curr) return true; if (val < p->val) p = p->left; else p = p->right; } return false; } bool dfs(TreeNode* root, TreeNode* curr, int k) { if (!curr) return false; if (search(root, curr, k - curr->val)) return true; return dfs(root, curr->left, k) || dfs(root, curr->right, k); }public: bool findTarget(TreeNode* root, int k) { return dfs(root, root, k); }}; int main() { TreeNode* root = new TreeNode(5); root->left = new TreeNode(3); root->right = new TreeNode(6); root->left->left = new TreeNode(2); root->left->right = new TreeNode(4); root->right->right = new TreeNode(7); Solution sol; std::cout << "Target 9: " << (sol.findTarget(root, 9) ? "true" : "false") << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N * H) - Space complexity:
O(H) recursion stack space