LeetCode 653 Two Sum IV - Input is a BST 解题报告
题目要求
Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
题目分析及思路
给定一个二叉搜索树和一个目标值,若该树中存在两个元素的和等于目标值则返回true。可以先获得树中所有结点的值列表,然后遍历每个值,判断目标值与该值的差是否也在该列表中,并保存每个值的判断结果。若有一个true则返回true。
python代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
vals = []
q = collections.deque()
q.append(root)
while q:
size = len(q)
for _ in range(size):
node = q.popleft()
if not node:
continue
vals.append(node.val)
q.append(node.left)
q.append(node.right)
ans = []
for v in vals:
if k-v in vals and k-v != v:
ans.append(True)
else:
ans.append(False)
if True in ans:
return True
else:
return False