
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.
1#include <vector>
2#include <iostream>
3
4struct TreeNode {
5 int val;
6 TreeNode* left;
7 TreeNode* right;
8 TreeNode(int x) : val(x), left(NULL), right(NULL) {}
9};
10
11void inorder(TreeNode* root, std::vector<int>& nums) {
12 if (!root) return;
13 inorder(root->left, nums);
14 nums.push_back(root->val);
15 inorder(root->right, nums);
16}
17
18bool findTarget(TreeNode* root, int k) {
19 std::vector<int> nums;
20 inorder(root, nums);
21 int l = 0, r = nums.size() - 1;
22 while (l < r) {
23 int sum = nums[l] + nums[r];
24 if (sum == k) return true;
25 else if (sum < k) l++;
26 else r--;
27 }
28 return false;
29}
30In this C++ solution, we collect the sorted elements using an inorder traversal. The two-pointer technique is used for finding two numbers summing to 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
Java's HashSet is used for efficient complement checks as the tree is traversed, validating potential sums of k early.