Two Sum IV - Input is a BST
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:
Example 2:
Analysis
https://leetcode.com/articles/two-sum-iv/
BFS + HashSet
广度优先搜索,level order traversal:每一个节点遍历时,在hashset里面找是否存在target - currentNode.val,每一层的左右子节点依次放入queue,同时在hashset里面存入当前遍历的节点:
Remove an element,pp, from the front of thequeuequeue.
Check if the elementk-pk−palready exists in thesetset. If so, return True.
Otherwise, add this element,ppto thesetset. Further, add the right and the left child nodes of the current node to the back of thequeuequeue.
Continue steps 1. to 3. till thequeuequeuebecomes empty.
Return false if thequeuequeuebecomes empty.
BST In-order Traversal + Two Pointers
先in-order遍历BST,输出到一个list,再对这个list用2 sum的方法找target即可,因为list排序过,因此用two pointers很方便。
Solution
BFS + HashSet - Time: O(n), Space O(n)
BST inorder + Two Pointers
Recursive + HashSet
Last updated