LeetCode 1214. Two Sum BSTs Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1214. Two Sum BSTs

Description

Given the roots of two binary search trees, root1 and root2, return true if and only if there is a node in the first tree and a node in the second tree whose values sum up to a given integer target.

 

Example 1:

Input: root1 = [2,1,4], root2 = [1,0,3], target = 5
Output: true
Explanation: 2 and 3 sum up to 5.

Example 2:

Input: root1 = [0,-10,10], root2 = [5,1,7,0,2], target = 18
Output: false

 

Constraints:

  • The number of nodes in each tree is in the range [1, 5000].
  • -109 <= Node.val, target <= 109

Solutions

Solution 1: In-order Traversal + Two Pointers

We perform in-order traversals on the two trees separately, obtaining two sorted arrays nums[0] and nums[1]. Then we use a two-pointer method to determine whether there exist two numbers whose sum equals the target value. The two-pointer method is as follows:

Initialize two pointers i and j, pointing to the left boundary of array nums[0] and the right boundary of array nums[1] respectively;

Each time, compare the sum x = nums[0][i] + nums[1][j] with the target value. If x = target, return true; otherwise, if x \lt target, move i one step to the right; otherwise, if x \gt target, move j one step to the left.

The time complexity is O(m + n), and the space complexity is O(m + n). Here, m and n are the number of nodes in the two trees respectively.

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 twoSumBSTs( self, root1: Optional[TreeNode], root2: Optional[TreeNode], target: int ) -> bool: def dfs(root: Optional[TreeNode], i: int): if root is None: return dfs(root.left, i) nums[i].append(root.val) dfs(root.right, i) nums = [[], []] dfs(root1, 0) dfs(root2, 1) i, j = 0, len(nums[1]) - 1 while i < len(nums[0]) and ~j: x = nums[0][i] + nums[1][j] if x == target: return True if x < target: i += 1 else: j -= 1 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 !