Sponsored
Sponsored
This approach leverages the properties of a Binary Search Tree (BST). By performing an inorder traversal on a BST, we can obtain a sorted list of its elements. Once we have this sorted list, the problem reduces to finding two distinct numbers in this sorted array that sum up to the given target, k
. This can efficiently be solved using the two-pointer technique.
Time Complexity: Perform O(n) for traversal and O(n) for two-pointer scan, hence O(n).
Space Complexity: O(n) to store the elements of the tree.
1function TreeNode(val, left = null, right = null) {
2 this.val = val;
3 this.left = left;
4 this.right = right;
5}
6
7var findTarget = function(root, k) {
8 const nums = [];
9 inorder(root, nums);
10 let left = 0, right = nums.length - 1;
11 while (left < right) {
12 const sum = nums[left] + nums[right];
13 if (sum === k) {
14 return true;
15 } else if (sum < k) {
16 left++;
17 } else {
18 right--;
19 }
20 }
21 return false;
22};
23
24function inorder(node, nums) {
25 if (!node) return;
26 inorder(node.left, nums);
27 nums.push(node.val);
28 inorder(node.right, nums);
29}
30
The JavaScript solution logs the inorder sequence to an array, applying the two-pointer method to search for the desired sum of k
.
This approach utilizes a hash set to store visited node values. We traverse the BST and for each node, check if k - node.val
exists in the hash set. If it does, then a pair adding to k
has been found.
Time Complexity: O(n), with a pass through each node.
Space Complexity: O(n) for storing nodes in the hash table.
1#include <iostream>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool findTarget(TreeNode* root, int k) {
std::unordered_set<int> set;
return find(root, k, set);
}
bool find(TreeNode* node, int k, std::unordered_set<int>& set) {
if (!node) return false;
if (set.find(k - node->val) != set.end()) return true;
set.insert(node->val);
return find(node->left, k, set) || find(node->right, k, set);
}
Utilizing the unique lookup capability of hash sets in C++, this solution tracks visited complements, early terminating if a match for k
is found.