【leetcode系列】【算法】【简单】两数之和 IV - 输入 BST(Binary Search Tree)

题目:

题目链接:https://leetcode-cn.com/problems/two-sum-iv-input-is-a-bst/

解题思路:

类似两数之和的解题思路

添加一个hash表保存已经遍历过的数字,只是需要将遍历方式修改为树的遍历方式

代码实现:

# 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:
        if not root:
            return False

        rec = set()
        stack = [root]
        while stack:
            node = stack[-1]
            stack.pop()
            other_num = k - node.val
            if other_num in rec:
                return True

            rec.add(node.val)
            if node.left:
                stack.append(node.left)

            if node.right:
                stack.append(node.right)

        return False
发布了138 篇原创文章 · 获赞 13 · 访问量 2448

猜你喜欢

转载自blog.csdn.net/songyuwen0808/article/details/105675827
今日推荐