[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 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
思路:
Two Sum的变种题,这次输入的是一个二叉树,还是用HashMap,然后遍历二叉树,用之前的方法找就行了。
还有一种方法是利用BST的性质,进行查找。
Java:
This method also works for those who are not BSTs. The idea is to use a hashtable to save the values of the nodes in the BST. Each time when we insert the value of a new node into the hashtable, we check if the hashtable contains k - node.val.
Time Complexity: O(n), Space Complexity: O(n).
public boolean findTarget(TreeNode root, int k) {
HashSet<Integer> set = new HashSet<>();
return dfs(root, set, k);
}
public boolean dfs(TreeNode root, HashSet<Integer> set, int k){
if(root == null)return false;
if(set.contains(k - root.val))return true;
set.add(root.val);
return dfs(root.left, set, k) || dfs(root.right, set, k);
}
Java:
The idea is to use a sorted array to save the values of the nodes in the BST by using an inorder traversal. Then, we use two pointers which begins from the start and end of the array to find if there is a sum k.
Time Complexity: O(n), Space Complexity: O(n).
public boolean findTarget(TreeNode root, int k) {
List<Integer> nums = new ArrayList<>();
inorder(root, nums);
for(int i = 0, j = nums.size()-1; i<j;){
if(nums.get(i) + nums.get(j) == k)return true;
if(nums.get(i) + nums.get(j) < k)i++;
else j--;
}
return false;
}
public void inorder(TreeNode root, List<Integer> nums){
if(root == null)return;
inorder(root.left, nums);
nums.add(root.val);
inorder(root.right, nums);
}
Java:
The idea is to use binary search method. For each node, we check if k - node.val exists in this BST.
Time Complexity: O(nh), Space Complexity: O(h). h is the height of the tree, which is logn at best case, and n at worst case.
public boolean findTarget(TreeNode root, int k) {
return dfs(root, root, k);
}
public boolean dfs(TreeNode root, TreeNode cur, int k){
if(cur == null)return false;
return search(root, cur, k - cur.val) || dfs(root, cur.left, k) || dfs(root, cur.right, k);
}
public boolean search(TreeNode root, TreeNode cur, int value){
if(root == null)return false;
return (root.val == value) && (root != cur)
|| (root.val < value) && search(root.right, cur, value)
|| (root.val > value) && search(root.left, cur, value);
}
Java:
public class Solution {
public boolean findTarget(TreeNode root, int k) {
List<Integer> list = new ArrayList<>();
inorder(root, list);
int i = 0;
int j = list.size() - 1;
while (i < j) {
int sum = list.get(i) + list.get(j);
if (sum == k) {
return true;
}
else if (sum < k) {
i++;
}
else {
j--;
}
}
return false;
}
public List<Integer> inorder(TreeNode root, List<Integer> list) {
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
list.add(root.val);
root = root.right;
}
return list;
}
}
Java:
public class Solution {
public boolean findTarget(TreeNode root, int k) {
Set<Integer> candidates = new HashSet<>();
Stack<TreeNode> stack = new Stack<>();
while (!stack.empty() || root != null) {
if (root != null) {
int val = root.val;
if (candidates.contains(val)) {
return true;
} else {
candidates.add(k - val);
}
stack.add(root);
root = root.left;
} else {
TreeNode node = stack.pop();
root = node.right;
}
}
return false;
}
}
Python: 递归遍历BST + Two Sum
class Solution(object):
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
self.dset = set()
self.traverse(root)
for n in self.dset:
if k - n != n and k - n in self.dset:
return True
return False
def traverse(self, root):
if not root: return
self.dset.add(root.val)
self.traverse(root.left)
self.traverse(root.right)
Python: wo, 160 ms, faster than 9.23% of Python online submissions
class Solution(object):
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
nums = []
self.dfs(root, nums)
lookup = [] for num in nums:
if k - num in lookup:
return True
lookup.append(num)
return False def dfs(self, root, res):
if not root:
return
res.append(root.val)
self.dfs(root.left, res)
self.dfs(root.right, res)
Python: 递归遍历BST + 利用BST性质进行检索
class Solution(object):
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
self.root = root
self.k = k
return self.findNumber(root)
def findNumber(self, root):
if not root: return False
node = self.root
n = self.k - root.val
if n != root.val:
while node:
if node.val == n: return True
if n > node.val: node = node.right
else: node = node.left
return self.findNumber(root.left) or self.findNumber(root.right)
Python:
class Solution:
def findTarget(self, root, k):
candidates = set()
stack = []
while stack or root:
if root:
val = root.val
if val in candidates:
return True
else:
candidates.add(k - val)
stack.append(root)
root = root.left
else:
node = stack.pop()
root = node.right
return False
C++:
bool findTarget(TreeNode* root, int k) {
unordered_set<int> set;
return dfs(root, set, k);
}
bool dfs(TreeNode* root, unordered_set<int>& set, int k){
if(root == NULL)return false;
if(set.count(k - root->val))return true;
set.insert(root->val);
return dfs(root->left, set, k) || dfs(root->right, set, k);
}
C++:
bool findTarget(TreeNode* root, int k) {
vector<int> nums;
inorder(root, nums);
for(int i = 0, j = nums.size()-1; i<j;){
if(nums[i] + nums[j] == k)return true;
(nums[i] + nums[j] < k)? i++ : j--;
}
return false;
}
void inorder(TreeNode* root, vector<int>& nums){
if(root == NULL)return;
inorder(root->left, nums);
nums.push_back(root->val);
inorder(root->right, nums);
}
C++:
bool findTarget(TreeNode* root, int k) {
return dfs(root, root, k);
}
bool dfs(TreeNode* root, TreeNode* cur, int k){
if(cur == NULL)return false;
return search(root, cur, k - cur->val) || dfs(root, cur->left, k) || dfs(root, cur->right, k);
}
bool search(TreeNode* root, TreeNode *cur, int value){
if(root == NULL)return false;
return (root->val == value) && (root != cur)
|| (root->val < value) && search(root->right, cur, value)
|| (root->val > value) && search(root->left, cur, value);
}
相似题目:
[LeetCode] 167. Two Sum II - Input array is sorted 两数和 II - 输入是有序的数组
[LeetCode] 170. Two Sum III - Data structure design 两数之和之三 - 数据结构设计
[LeetCode] 653. Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树的更多相关文章
- [LeetCode] 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] 167. Two Sum II - Input array is sorted 两数和 II - 输入是有序的数组
Given an array of integers that is already sorted in ascending order, find two numbers such that the ...
- Leetcode653.Two Sum IV - Input is a BST两数之和4-输入BST
给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true. struct TreeNode { int val; struct TreeNode * ...
- 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 ...
- 167 Two Sum II - Input array is sorted 两数之和 II - 输入有序数组
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数.函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2.请注意,返回的下标值(i ...
- 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; 完
随机推荐
- python学习之鼠标事件&键盘事件
driver.maximize_window() 浏览器最大化 ActionChains类与输入事件 1:from selenium.webdriver.common.action_chains ...
- 【python】Requests的三种参数请求方式
URL参数请求: import requests ''' URL Parameters 请求方式: URL参数 例如: 以get 方式请求http://httpbin.org/get?first_na ...
- 关于H5判定区域里面滑动到底部,加载更多的总结
1.如何判定H5中滑动到底部,然后加载更多的功能实现. 思路:我们需要设定一个固定高度的盒子,然后我们利用scroll来监听滚动,当scrollTop(滚动的距离) + clientHeight(页面 ...
- 权限管理(chown、chgrp、umask)
对于文件或目录的权限的修改,只能管理员和文件的所有者拥有此权限,但是对于文件或目录的的所有者的更改,只有管理员拥有此权限(虽然普通用户创建的文件或目录,用户也不能修改文件或目录的所有者). 1.cho ...
- cube.js 新版本试用preosto
cube.js 新的版本添加了更多的数据库的支持,但是目前cubejs-cli 以及官方文档问题还挺多,使用不清晰,文档有明显的错误 以下演示presto 数据库的使用 环境准备 安装新版本的cube ...
- 保护 SSH 的三把锁
转自:https://www.ibm.com/developerworks/cn/aix/library/au-sshlocks/index.html 简介 如果需要远程访问计算机并启用了 Secur ...
- NOI 2019 游记
day -1 去报了个到,顺便买了一大堆衣服. 感觉学校饭堂不太行. day 0 上午是开幕式,. 下午是笔试,顺利获得 \(100\) 分. day 1 先看题. 第一题看到 \(At^2+Bt+C ...
- Ajax.BeginForm 不执行OnSuccess
今天用MVC做了一个表单提交,使用Ajax.BeginForm ,但是碰到一个奇怪的问题OnSuccess回调函数不执行.后来经过多次尝试才发现要引用两个东西 1.<script src=&qu ...
- 3D数据采集和重建
3D数据采集和重建是从传感器数据生成三维或时空模型.一般而言,这些技术和理论适用于大多数或所有传感器类型,包括光学,声学,激光扫描,[1]雷达,热学,[2]地震.[3][4] 内容 · ...
- 【转】Java 8新特性(四):新的时间和日期API
Java 8另一个新增的重要特性就是引入了新的时间和日期API,它们被包含在java.time包中.借助新的时间和日期API可以以更简洁的方法处理时间和日期. 在介绍本篇文章内容之前,我们先来讨论Ja ...