EasyNo. 0653
Two Sum IV - Input is a BST — LeetCode 653 Python Solution
- Pattern
- Two Pointers
- Topics
- Tree, Depth-First Search, Breadth-First Search, Binary Search Tree, Hash Table, Two Pointers, Binary Tree
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given the root of a binary search tree and an integer k, return true if there exist two elements in the BST such that their sum is equal to k, or false otherwise.
Example
- Input
- root = [5,3,6,2,4,null,7], k = 9
- Output
- true
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
def dfs(root):
if root is None:
return False
if k - root.val in vis:
return True
vis.add(root.val)
return dfs(root.left) or dfs(root.right)
vis = set()
return dfs(root)Complexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 653. Two Sum IV - Input is a BST is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0001 | Two Sum | Easy |
| 0863 | All Nodes Distance K in Binary Tree | Medium |
| 0865 | Smallest Subtree with all the Deepest Nodes | Medium |
| 0987 | Vertical Order Traversal of a Binary Tree | Hard |
| 1123 | Lowest Common Ancestor of Deepest Leaves | Medium |
| 1261 | Find Elements in a Contaminated Binary Tree | Medium |
Frequently asked questions
- How hard is LeetCode 653. Two Sum IV - Input is a BST?
LeetCode 653. Two Sum IV - Input is a BST is rated Easy on LeetCode.
- What is the time complexity of LeetCode 653. Two Sum IV - Input is a BST?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 653. Two Sum IV - Input is a BST?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 653. Two Sum IV - Input is a BST cover?
LeetCode 653. Two Sum IV - Input is a BST is tagged Tree, Depth-First Search, Breadth-First Search, Binary Search Tree, Hash Table, Two Pointers and Binary Tree on LeetCode.