[leetcode] 653. Two Sum IV - Input is a BST @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/88714063

原题

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.

Example 1:

Input:
5
/
3 6
/ \
2 4 7

Target = 9

Output: True

Example 2:

Input:
5
/
3 6
/ \
2 4 7

Target = 28

Output: False

解法1

中序遍历, 将节点的值放入列表, 然后遍历列表, 查找是否存在两个数的和为k
Time: O(2*n)
Space: 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
        """
        l = []
        def inOrder(root):
            if not root:
                return
            inOrder(root.left)
            l.append(root.val)
            inOrder(root.right)
        
        inOrder(root)
        for n in l:
            if k-n in l and k-n!= n:
                return True
        return False

解法2

BFS. 将每一层的节点放入队列, 检查已见过的节点中是否有一个节点, 使得与当前节点的和等于k.

代码

# 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
        """
        if not root: return False
        q = [root]
        seen = set()
        while q:
            for node in q:
                if k-node.val in seen:
                    return True
                else:
                    seen.add(node.val)
            q = [kid for node in q for kid in (node.left, node.right) if kid]
        return False

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/88714063