LeetCode 0653. Two Sum IV - Input is a BST Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0653. Two Sum IV - Input is a BST

Description

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

Solutions

Solution 1

PythonJavaC++GoTypeScriptRust
# 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)(code-box)

Solution 2

PythonJavaC++GoTypeScript
# 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: q = deque([root]) vis = set() while q: for _ in range(len(q)): node = q.popleft() if k - node.val in vis: return True vis.add(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) return False(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !