题目
给出一个二叉搜索树和一个目标值,找到两个节点值得和为给定的目标值。
Python题解
class Solution(object):
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
if root is None:
return False
num_set = set()
queue = [root]
while len(queue):
node = queue.pop(0)
another_val = k - node.val
if another_val in num_set:
return True
num_set.add(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return False
本文介绍了一种使用Python实现的算法,该算法能在给定的二叉搜索树中寻找两个节点,使这两个节点的值之和等于指定的目标值。通过广度优先搜索和集合操作实现了高效的查找。
429

被折叠的 条评论
为什么被折叠?



