[leetcode]653. Two Sum IV - Input is a BST(Python)

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

题目描述

Category:Easy Tree

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.
在这里插入图片描述

题目理解

给定一棵二叉搜索树和目标数,如果数中任意两个元素之和等于目标数返回true。

解题思路

BFS

把pop(0)的方式进行了简化,直接使用for就可以完成列表遍历,如果列表改变了也没问题。(我好像也跟着作者学了一种BFS新的写法!很强了!)
使用set()保存已经遍历了的数字,作为存储。
思路借鉴:https://blog.csdn.net/fuxuemingzhu/article/details/79120732

class Solution:
	# Runtime: 72ms 86.36%  MemoryUsage: 15MB 100.00%
    def findTarget1(self, root: TreeNode, k: int) -> bool:
        if not root:
            return False
        bfs, s = [root], set()
        for i in bfs:
            if k - i.val in s:
                return True
            s.add(i.val)
            if i.left:
                bfs.append(i.left)
            if i.right:
                bfs.append(i.right)
        return False

BFS的常规写法:

class Solution:
	# Runtime: 80ms 58.53%  MemoryUsage: 14.9MB 100.00%
    def findTarget2(self, root: TreeNode, k: int) -> bool:
        que = collections.deque()
        que.append(root)
        res = set()
        while que:
            for _ in range(len(que)):
                node = que.popleft()
                if not node:
                    continue
                if k - node.val in res:
                    return True
                res.add(node.val)
                que.append(node.left)
                que.append(node.right)
        return False

作者的方法比我快的原因应该在于省去了二次遍历判断的时间,直接用k减去当前节点的值,判断该值是否在set中,这种判断方式好像会更快一点。

MyMethod

中序遍历 + Two Sum问题
用res数组记录二叉搜索树中序遍历的结果,数组中元素按顺序递增,从首尾开始判断两数之和是否等于k,若大于k,大数减小(right-1);若小于k,小数增大(left+1);若等于k,返回true。

class Solution:
    # Runtime: 84ms 46.63%  MemoryUsage: 14.9MB 100.00%
    def findTarget(self, root: TreeNode, k: int) -> bool:
        if root is None:
            return []
        res = []
        self.in_order(root, res)
        left, right = 0, len(res) - 1
        while left < right and left >= 0 and right < len(res):
            if res[left] + res[right] == k:
                return True
            elif res[left] + res[right] > k:
                right -= 1
            else:
                left += 1
        return False

    def in_order(self, root, res):
        if root is None:
            return
        self.in_order(root.left, res)
        res.append(root.val)
        self.in_order(root.right, res)

Time

2020.3.21 快乐周六也要刷题!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值