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: 5 / \ 3 6 / \ \ 2 4 7 Target = 9 Output: True
Example 2:
Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 28 Output: False
分析
只要把二叉树的元素提取到一个列表中,那么我们就可以把上面这个问题转化为已知的Two Sum问题。
伪代码
# 提取以rootNode为顶点的二叉树的元素到list
getBinarySearchTreeElements(rootNode, list)
if rootNode is null:
return
getBinarySearchTreeElements(rootNode.left, list)
append rootNode.value to tail of list
getBinarySearchTreeElements(rootNode.right, list)