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.
1import java.util.ArrayList;
2
3public class Solution {
4 public boolean findTarget(TreeNode root, int k) {
5 ArrayList<Integer> nums = new ArrayList<>();
6 inorder(root, nums);
7 int left = 0, right = nums.size() - 1;
8 while (left < right) {
9 int sum = nums.get(left) + nums.get(right);
10 if (sum == k) {
11 return true;
12 } else if (sum < k) {
13 left++;
14 } else {
15 right--;
16 }
17 }
18 return false;
19 }
20
21 private void inorder(TreeNode node, ArrayList<Integer> nums) {
22 if (node == null) return;
23 inorder(node.left, nums);
24 nums.add(node.val);
25 inorder(node.right, nums);
26 }
27
28 class TreeNode {
29 int val;
30 TreeNode left;
31 TreeNode right;
32 TreeNode(int x) { val = x; }
33 }
34}
35
This Java solution uses an ArrayList
to store sorted nodes. With two pointers, the sum check for k
is performed efficiently.
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
By storing visited values in a set
, the Python solution keeps track of necessary complements, rapidly determining whether k
can be formed.