Two Sum IV - Input is a BST

update Aug 18, 2017 22:52

LeetCodearrow-up-right

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

Basic Idea:

有两种方法: 1. 遍历bst,利用hashSet看之前有无出现 target - curr.val; 2. in order 遍历bst,结果存入数组,则此时数组已经排序,然后用 two pointers 的方法,i j 从最左端和最右端开始,如果和大于target,则 j--, 如果小于,则 i++;

Python Code:

方法 1:

方法 2:

udpate Dec23, 2017 0:57

Update

Java Code: