树--给定二叉搜索树(BST)和target

[653. Two Sum IV - Input is a BST(https://leetcode.com/problems/two-sum-iv-input-is-a-bst/)

题目描述

给定二叉搜索树(BST)和target。如果BST存在两个元素和为target,返回true;否则返回false

例子 略 思想 (法12 - 借助辅助字典,没有用到BST这个条件) 两个数的和为target。借助辅助字典,将已遍历过的结点放入字典中。 (法3 - 中序遍历)BST - 左根右 中序遍历存储,然后双指针。

解法1 递归 + 辅助字典。复杂度:时间O(n),空间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 __init__(self):
        self.dic = {}
    def findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        if not root:
            return False
        if k - root.val in self.dic:
            return True
        self.dic[root.val] = 0
        return self.findTarget(root.left, k) or self.findTarget(root.right, k)
解法2 层次遍历 + 辅助字典。复杂度:时间O(n),空间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
        """
        dic = {}
        queue = [root]
        while queue and root:
            node = queue.pop(0)
            if k - node.val in dic:
                return True
            dic[node.val] = 0
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right) 
        return False
解法3 中序遍历 + 双指针。复杂度:时间O(n),空间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
        """
        arr = []
        self.inOrder(root, arr)
        left, right = 0, len(arr) - 1
        while left < right:
            temp = arr[left] + arr[right]
            if temp == k:
                return True
            if temp > k:
                right -= 1
            else:
                left += 1
        return False
         
    def inOrder(self, root, arr):
        if not root:
            return
        self.inOrder(root.left, arr)
        arr.append(root.val)
        self.inOrder(root.right, arr)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值