作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/

题目描述

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

题目大意

判断一个BST中是否存在两个节点的和等于指定的K.

解题方法

方法一:BFS

这个题又让我学到了,原来bfs还可以这么写。

原来认为bfs是通过append和pop(0)的方式进行计算的,这个答案把pop(0)的方式进行了简化,直接使用for就可以完成列表遍历,如果列表改变了也没问题。

使用set()保存已经遍历了的数字,作为存储。

比如下面用例的结果如下:
用例:

[5,3,6,2,4,null,7]
9

结果:

5
[5, 3, 6]
3
[5, 3, 6, 2, 4]
6
# 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
bfs, s = [root], set()
for i in bfs:
print i.val
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)
print([b.val for b in bfs])
return False

二刷的时候,使用BFS的标准写法,如下:

# 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
"""
que = collections.deque()
que.append(root)
res = set()
while que:
size = len(que)
for _ in range(size):
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

方法二:DFS

直接使用DFS进行判断也可以。这里又有两种写法,第一种是中序遍历成有序数组,然后进行一个2sum操作;另一种是在DFS的过程中就进行判断,如果找到即停止。

中序遍历解法如下:

# 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
"""
res = self.inOrder(root)
resset = set(res)
for num in res:
if k != 2 * num and k - num in resset:
return True
return False def inOrder(self, root):
if not root:
return []
res = []
res.extend(self.inOrder(root.left))
res.append(root.val)
res.extend(self.inOrder(root.right))
return res

DFS过程中进行判断:

# 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
"""
res = set()
def inOrder(root):
if not root:
return False
if k - root.val in res:
return True
res.add(root.val)
return inOrder(root.left) or inOrder(root.right)
return inOrder(root)

日期

2018 年 1 月 21 日
2018 年 11 月 11 日 —— 剁手节快乐

【LeetCode】653. Two Sum IV - Input is a BST 解题报告(Python)的更多相关文章

  1. LeetCode 653 Two Sum IV - Input is a BST 解题报告

    题目要求 Given a Binary Search Tree and a target number, return true if there exist two elements in the ...

  2. [LeetCode] 653. Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树

    Given a Binary Search Tree and a target number, return true if there exist two elements in the BST s ...

  3. LeetCode - 653. Two Sum IV - Input is a BST

    Given a Binary Search Tree and a target number, return true if there exist two elements in the BST s ...

  4. LeetCode 653. Two Sum IV – Input is a BST

    Given a Binary Search Tree and a target number, return true if there exist two elements in the BST s ...

  5. leetcode 1.Two Sum 、167. Two Sum II - Input array is sorted 、15. 3Sum 、16. 3Sum Closest 、 18. 4Sum 、653. Two Sum IV - Input is a BST

    1.two sum 用hash来存储数值和对应的位置索引,通过target-当前值来获得需要的值,然后再hash中寻找 错误代码1: Input:[3,2,4]6Output:[0,0]Expecte ...

  6. 【Leetcode_easy】653. Two Sum IV - Input is a BST

    problem 653. Two Sum IV - Input is a BST 参考 1. Leetcode_easy_653. Two Sum IV - Input is a BST; 完

  7. [LeetCode&Python] Problem 653. Two Sum IV - Input is a BST

    Given a Binary Search Tree and a target number, return true if there exist two elements in the BST s ...

  8. 【leetcode】653. Two Sum IV - Input is a BST

    Given the root of a Binary Search Tree and a target number k, return true if there exist two element ...

  9. 653. Two Sum IV - Input is a BST

    Given a Binary Search Tree and a target number, return true if there exist two elements in the BST s ...

随机推荐

  1. Excel-转换单元格格式的函数或“方法”汇总

    14.转换单元格格式的函数或"方法"汇总 =value(单元格)  #转换为数值 =A1&""                   #转换A1为文本 = ...

  2. Redis | Redis常用命令及示例总结(API)

    目录 前言 1. Key(键) 1.1 键的基本操作功能 del move sort rename renamenx migrate 1.2 键的获取功能 type exists randomkey ...

  3. day03 部署NFS服务

    day03 部署NFS服务 NFS的原理 1.什么是NFS 共享网络文件存储服务器 2.NFS的原理 1.用户访问NFS客户端,将请求转化为函数 2.NFS通过TCP/IP连接服务端 3.NFS服务端 ...

  4. stm32串行设备接口SPI控制max31865

    本人是刚入行的嵌入式,之前也没有多少项目经验,故在公司的这几个月里,可谓是如履薄冰,对于公司不同项目使用的不同的设备之多,数据手册之繁杂,让我不禁望洋兴叹,故而不愿意放弃周末这大好的自我提升时间,努力 ...

  5. 在 Apple Silicon Mac 上 DFU 模式恢复 macOS 固件

    DFU 模式全新安装 macOS Big Sur 或 macOS Monterey 请访问原文链接:https://sysin.org/blog/apple-silicon-mac-dfu/,查看最新 ...

  6. Java打jar包详解

    Java打jar包详解 一.Java打jar包的几种方式https://www.cnblogs.com/mq0036/p/8566427.html 二.MANIFEST.MF文件详解https://w ...

  7. 命令行方式运行hadoop程序

    1,写一个java代码.*.java.(这里从example 拷贝一个过来作为测试) cp src/examples/org/apache/hadoop/examples/WordCount.java ...

  8. Java实现邮件收发

    一. 准备工作 1. 传输协议 SMTP协议-->发送邮件: 我们通常把处理用户smtp请求(邮件发送请求)的服务器称之为SMTP服务器(邮件发送服务器) POP3协议-->接收邮件: 我 ...

  9. Java线程安全性-原子性工具对比

    synchronized 不可中断锁,适合竞争不激烈的场景,可读性好,竞争激烈时性能下降很快 Lock 可中断锁,多样化同步,竞争激烈时能维持常态 Atomic 竞争激烈时能维持常态,比Lock性能还 ...

  10. 9.Vue.js 监听属性

    本章节,我们将为大家介绍 Vue.js 监听属性 watch,我们可以通过 watch 来响应数据的变化. 以下实例通过使用 watch 实现计数器: <div id = "app&q ...