Skip to main content

653. Two Sum IV - Input is a BST

https://leetcode.com/problems/two-sum-iv-input-is-a-bst/

Python

DFS

  • Remember the path and do postorder traversal
  • Did NOT use the advantage from BST...
class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
def dfs(node, targets: set):
if not node:
return False
if node.val in targets:
return True

targets.add(k-node.val)

return dfs(node.left, targets) or dfs(node.right, targets)

return dfs(root, set())