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
题目给定两棵二叉搜索树和一个目标数,问是否在两棵树中各存在一个节点使得两个节点值的和等于目标数。如果看过653. Two Sum IV - Input is a BST中的解法,就会发现这题更简单。做这两道题的前提是要求对二叉搜索树的中序遍历很熟悉。
对于第一棵树可以采用常规中序遍历迭代法,从最小值节点(树的最左侧节点)开始按升序遍历;对于第二棵树可以采用变形中序遍历迭代法,从最大值节点(树的最右侧节点)开始按降序遍历;
结合两棵树的中序遍历,如果遍历的两个当前节点和小于目标数,则第一棵树中序遍历往后移动一个节点;如果大于目标数,则第二棵树中序遍历往前移动一个节点。直到找到和等于目标数为止。如果有一棵树遍历完了还没找到就说明不存在。
# 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:
st1, st2 = [], []
node = root1
while node:
st1.append(node)
node = node.left
node = root2
while node:
st2.append(node)
node = node.right
while st1 and st2:
node1, node2 = st1[-1], st2[-1]
if node1.val + node2.val == target:
return True
if node1.val + node2.val < target:
st1.pop()
if node1.right:
node1 = node1.right
while node1:
st1.append(node1)
node1 = node1.left
else:
st2.pop()
if node2.left:
node2 = node2.left
while node2:
st2.append(node2)
node2 = node2.right
return False