Problem
Given a binary search tree T, where each node contains a positive integer, and an integer K, you have to find whether or not there exist two different nodes A and B such that A.value + B.value = K.
Return 1 to denote that two such nodes exist. Return 0, otherwise.
OR
Given the root
of a Binary Search Tree and a target number k
, return true
if there exist two elements in the BST such that their sum is equal to the given target.
Notes: Your solution should run in linear time and not take memory more than O(height of T).
Assume all values in BST are distinct.
Examples
Example 1:
|
|
|
|
Example 2:
|
|
|
|
Solution
Method 1 - Using a Hashset and Dfs
This method works for any tree, so it doesn’t take care of features offered by BST.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)
assuming recursion stack
Method 2 - Create Sorted Array Using Inorder Traversal and Apply 2 Sum
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)
storing inorder traversal
Method 3 - Using BST Properties
The idea is to use binary search method. For each node, we check if k - node.val
exists in this BST.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n*h)
- 🧺 Space complexity:
O(h)
,h
is the height of the tree, which islogn
at best case, andn
at worst case.
Method 4 - Using BST Iterator
Algo
Using BST Iterator - .
- Since our Binary Tree is a Binary Search Tree, when we traverse elements in-order, elements are sorted. We have seen that in #Method 2 - Create Sorted Array Using Inorder Traversal and Apply 2 Sum.
- But why not use Binary Search Tree BST Inorder Iterator. Then, we can iterate in-order with O(h) time complexity.
- Since our elements are sorted, we can use Two Pointer to search a pair of
(left, right)
so thatleft + right = k
, whereleft
point to left element in the BST,right
point to right element in the BST.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the number of nodes in the BST. - 🧺 Space complexity:
O(h)
, whereh
is the height of the BST. The size ofstack
is up toO(h)
.