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}
40
This 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
By storing visited values in a set
, the Python solution keeps track of necessary complements, rapidly determining whether k
can be formed.