[653. Two Sum IV - Input is a BST(https://leetcode.com/problems/two-sum-iv-input-is-a-bst/)
题目描述
给定二叉搜索树(BST)和target。如果BST存在两个元素和为target,返回true;否则返回false
例子 略 思想 (法1、2 - 借助辅助字典,没有用到BST这个条件) 两个数的和为target。借助辅助字典,将已遍历过的结点放入字典中。 (法3 - 中序遍历)BST - 左根右 中序遍历存储,然后双指针。
解法1 递归 + 辅助字典。复杂度:时间O(n),空间O(n)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.dic = {}
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
if not root:
return False
if k - root.val in self.dic:
return True
self.dic[root.val] = 0
return self.findTarget(root.left, k) or self.findTarget(root.right, k)
解法2 层次遍历 + 辅助字典。复杂度:时间O(n),空间O(n)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
dic = {}
queue = [root]
while queue and root:
node = queue.pop(0)
if k - node.val in dic:
return True
dic[node.val] = 0
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return False
解法3 中序遍历 + 双指针。复杂度:时间O(n),空间O(n)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
arr = []
self.inOrder(root, arr)
left, right = 0, len(arr) - 1
while left < right:
temp = arr[left] + arr[right]
if temp == k:
return True
if temp > k:
right -= 1
else:
left += 1
return False
def inOrder(self, root, arr):
if not root:
return
self.inOrder(root.left, arr)
arr.append(root.val)
self.inOrder(root.right, arr)