653. 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:

Input:
5
/
3 6
/ \
2 4 7

Target = 9

Output: True

Example 2:

Input:
5
/
3 6
/ \
2 4 7

Target = 28

Output: False

class Solution:
    def findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        list = []
        def preorder(root):
            if root == None:
                return
            list.append(root.val)
            preorder(root.left)
            preorder(root.right)
        preorder(root)
        for i in range(len(list)):
            if k-list[i] in list[i+1:]:
                return True
        return False
posted @ 2018-09-29 10:56  bernieloveslife  阅读(100)  评论(0编辑  收藏  举报