Two Sum IV - Input is a BST
Easy · Hash Table, Two Pointers, Tree, Depth-First Search, Breadth-First Search, Binary Search Tree, Binary Tree
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 1
Input: root = [5,3,6,2,4,null,7], k = 9 Output: true
Example 2
Input: root = [5,3,6,2,4,null,7], k = 28 Output: false
Constraints
- The number of nodes in the tree is in the range [1, 104].
- -104 <= Node.val <= 104
- root is guaranteed to be a valid binary search tree.
- -105 <= k <= 105
Starter code (python)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def findTarget(self, root, k):
"""
:type root: Optional[TreeNode]
:type k: int
:rtype: bool
"""
Related problems
- Two Sum (Easy)
- Longest Substring Without Repeating Characters (Medium)
- Longest Palindromic Substring (Medium)
Previous: 2 Keys Keyboard · Next: Maximum Binary Tree · All problems
Zepruv is a technical interview practice platform. Read any problem for free; sign in to run your code, submit and keep your progress.