Reference: LeetCode
Difficulty: Easy
Problem
Given a Binary Search Tree and a target number, return
true
if there exist two elements in the BST such that their sum is equal to the given target.
Example:
1 | Input: |
Analysis
Hash Set
Using any traversal is fine.
Note: Duplicates are allowed.
1 | public boolean findTarget(TreeNode root, int k) { |
Time: $O(N)$
Space: $O(N)$
Inorder + Two Pointers
Basically, we convert the BST tree to a sorted list and then apply the two-pointer method.
Time: $O(N)$
Space: $O(N)$