【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 ...
随机推荐
- 8.Maximum Depth of Binary Tree
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...
- 巩固java第五天
巩固内容: HTML 实例解析 <p> 元素: <p>这是第一个段落.</p> 这个 <p> 元素定义了 HTML 文档中的一个段落. 这个元素拥有一个 ...
- IDEA高颜值之最吸引小姐姐插件集合!让你成为人群中最靓的那个崽!
经常有小伙伴会来找TJ君,可能觉得TJ君比较靠谱,要TJ君帮忙介绍女朋友.TJ君一直觉得程序猿是天底下最可爱的一个群体,只不过有时候不善于表达自己的优秀,所以TJ君今天准备介绍几款酷炫实用的IDEA插 ...
- acre, across
acre The acre is a unit of land area used in the imperial and US customary systems. It is traditiona ...
- 零基础学习java------31---------共享单车案例,html快速入门(常见标签,get和post的区别)
一 .单车案例 二. HTML快速入门 红字表示要掌握的内容 超文本标记语言,此处的标记指的即是关键字,其用处是用来写页面(展示数据). 语法:(1)./当前目录:../ 父级目录 (2)注释符号: ...
- C++之无子数
题目如下: 1 #include <iostream> 2 3 using namespace std; 4 5 6 bool isThisNumhaveChild(int num); 7 ...
- linux 挂载本地iso
mount -t iso9660 -o loop /mnt/temp/rhel-server-6.5-i386-dvd.iso /mnt/cdrom -t :设备类型 iso9660是指CD-ROM光 ...
- ORACLE DBMS_ROWID包详解
这个包在11gR2中有11个函数或存储: 1. 根据给定参数返回一个rowid --根据给定参数返回一个rowid FUNCTION rowid_create(rowid_type IN NUMBER ...
- linux 定时导出sql查询结果文件
如果想在服务器端生成sql查询结果的txt文件. 大体思路就是: 1.创建一个到处txt文件的sql脚本. set ARRAYSIZE 50 --从数据库往客户端一次发送记录数 set linesiz ...
- Linux学习 - 网络命令
一.write 1 功能 给指定在线用户发信息,以Ctrl + D保存结束 2 语法 write <用户名> [信息] 二.wall(write all) 1 功能 给所有在线用户发送 ...