题目描述:
自己的提交:
class Solution: def twoSumBSTs(self, root1: TreeNode, root2: TreeNode, target: int) -> bool: if not root1 :return root_copy = root2 while root1 and root_copy: if root1.val + root_copy.val < target: root_copy = root_copy.right elif root1.val + root_copy.val > target: root_copy = root_copy.left else:return True if self.twoSumBSTs(root1.left,root2,target): return True if self.twoSumBSTs(root1.right,root2,target): return True return False
另:
class Solution(object): def twoSumBSTs(self, root1, root2, target): ans1 = [] def dfs1(node): if node: dfs1(node.left) ans1.append(node.val) dfs1(node.right) ans2 = [] def dfs2(node): if node: dfs2(node.left) ans2.append(node.val) dfs2(node.right) dfs1(root1) dfs2(root2) seen = set(ans1) for x in ans2: if target-x in seen: return True return False
优化:
class Solution: def twoSumBSTs(self, root1: TreeNode, root2: TreeNode, target: int) -> bool: def conv(root): if not root: return [] else: return [root.val] + conv(root.left) + conv(root.right) r1 = conv(root1) r2 = conv(root2) r1 = set(r1) r2 = set(r2) for i in r1: if target - i in r2: return True return False