
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.
1using System;
2using System.Collections.Generic;
3
4public class TreeNode {
5 public int val;
6 public TreeNode left;
7 public TreeNode right;
8 public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
9 this.val = val;
10 this.left = left;
11 this.right = right;
12 }
13}
14
15public class Solution {
16 public bool FindTarget(TreeNode root, int k) {
17 List<int> nums = new List<int>();
18 Inorder(root, nums);
19 int l = 0, r = nums.Count - 1;
20 while (l < r) {
21 int sum = nums[l] + nums[r];
22 if (sum == k) {
23 return true;
24 } else if (sum < k) {
25 l++;
26 } else {
27 r--;
28 }
29 }
30 return false;
31 }
32
33 private void Inorder(TreeNode node, List<int> nums) {
34 if (node == null) return;
35 Inorder(node.left, nums);
36 nums.Add(node.val);
37 Inorder(node.right, nums);
38 }
39}
40This C# code captures nodes in ascending order using an inorder traversal. With the two-pointer method, it finds if two numbers total 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.