653. 两数之和 IV - 输入 BST

exiaohu 于 2022-03-21 发布

题目链接:653. 两数之和 IV - 输入 BST

遍历一次二叉树,查看是否有符合条件的两个元素。

暴力实现,不考虑剪枝,遍历顺序不重要。

class Solution:
    def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
        if root is None:
            return False

        stack, visited = [root], set()
        while stack:
            node = stack.pop()

            if k - node.val in visited:
                return True

            visited.add(node.val)

            if node.right is not None:
                stack.append(node.right)
            if node.left is not None:
                stack.append(node.left)

        return False