【LeetCode】653. Two Sum IV - Input is a BST 解题报告(Python)
作者: 负雪明烛
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)的更多相关文章
- 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 ...
- [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 ...
- 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 ...
- 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 ...
- 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 ...
- 【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; 完
- [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 ...
- 【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 ...
- 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 ...
随机推荐
- 【Redis集群原理专题】分析一下相关的Redis集群模式下的脑裂问题!
技术格言 世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程. 什么是脑裂 字面含义 首先,脑裂从字面上理解就是脑袋裂开了,就是思想分家了,就是有了两个山头,就是有了 ...
- java的缓冲流及使用Properties集合存取数据(遍历,store,load)
缓冲流 概述 字节缓冲流:BufferedInputStream,BufferedOutputStream 字符缓冲流:BufferedReader,BufferedWriter 缓冲流原理 缓冲区是 ...
- Elasticsearch【基础入门】
目录 一.操作index 1.查看index 2.增加index 3.删除index 二.操作index 1.新增document 2.查询type 全部数据 3.查找指定 id 的 document ...
- 【Reverse】每日必逆0x01
附件:https://files.buuoj.cn/files/7458c5c0ce999ac491df13cf7a7ed9f1/SimpleRev 题解 查壳 64位ELF文件,无壳 IDApro处 ...
- 使用Rapidxml重建xml树
需求 : 重建一棵xml树, 在重建过程中对原来的标签进行一定的修改. 具体修改部分就不给出了, 这里只提供重建部分的代码 code : /****************************** ...
- implicit declaration of function 'NSFileTypeForHFSTypeCode' is invalid in c99
问题:implicit declaration of function 'NSFileTypeForHFSTypeCode' is invalid in c99 解决办法: 在出现该问题的函数前后加上 ...
- 2.8 GO 参数传递
简单将GO中参数传递分为三类 数字.字符.字符串等类型 结构体 方法 GO的方法本身就是地址的入口,打印一个方法输出的是这个方法的地址 func test_func(){ //0x488a30 fmt ...
- Druid数据库监控
一.简介 Druid是阿里开源的一个JDBC应用组件, 其包括三部分: DruidDriver: 代理Driver,能够提供基于Filter-Chain模式的插件体系. DruidDataSource ...
- 【Linux】【Shell】【Basic】条件测试和变量
bash脚本编程 脚本文件格式: 第一行,顶格:#!/bin/bash 注释信息:# 代码注释: 缩进,适度添加空白行: ...
- new Date()与setDate()参数
New Date()与setDate()参数 相信网上已经有很多关于日期的文章了,这里只是我自己再工作中遇到的问题然后加以总结: new Date() new Date() 一共有六种形式,五种带参数 ...