
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.
1using System.Collections.Generic;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public bool FindTarget(TreeNode root, int k) {
HashSet<int> set = new HashSet<int>();
return Find(root, k, set);
}
private bool Find(TreeNode node, int k, HashSet<int> set) {
if (node == null) return false;
if (set.Contains(k - node.val)) return true;
set.Add(node.val);
return Find(node.left, k, set) || Find(node.right, k, set);
}
}
The C# solution employs a HashSet for its complement query ability, detecting when k can be achieved with visited nodes.