LC 653. Two Sum IV - Input is a BST
Problem Statement
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.
Examples
1 | Input: |
1 | Input: |
Thought
The strategy is the same as finding two elements in a sorted array that sum of them equals to k. But we cannot perform random access on a BST. The key point of this question is to either rebuild the sorted array by inorder traversal through BST or iteratively go through the BST also in inorder order.
There’s a clear and efficient solution posted in the discussion that he implemented a BST Iterator to simulate the two pointer sweeping in the sorted array version.
I try to implement one with some modification to make it more clear and readable.
Time Complexity
The traverse operation cost O(1) and the loop stop when all the elements are visited once. So overall complexity is O(N).
Full Solution
1 | /** |