653. Two Sum IV - Input is a BST (Easy)
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
思路:递归遍历BST(Binary Search Tree)
class Solution: def findTarget(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ self.root = root self.k = k return self.searchNumber(root) def searchNumber(self, root): if not root: return False node = self.root n = self.k - root.val if n != root.val: while node: if node.val == n: return True if n > node.val: node = node.right else: node = node.left return self.searchNumber(root.left) or self.searchNumber(root.right)