Two Sum IV - Input is a BST LT653
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
Idea 1. Similar to Two Sum LT1, use set to record the element while looping the BST and check if target - num exists.
Time complexity: O(n)
Space complexity: O(h) + O(n)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private boolean findHelper(TreeNode root, int k, Set<Integer> record) {
if(root == null) {
return false;
} if(record.contains(k - root.val)) {
return true;
}
record.add(root.val);
return findHelper(root.left, k, record)
|| findHelper(root.right, k, record);
}
public boolean findTarget(TreeNode root, int k) {
return findHelper(root, k, new HashSet<Integer>());
}
}
Idea 2 BFS + Set, insted of DFS(preorder, inorder, postordal) traversal like idea 1
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public boolean findTarget(TreeNode root, int k) {
if(root == null) {
return false;
}
Deque<TreeNode> queue = new ArrayDeque<>();
Set<Integer> record = new HashSet<>();
queue.add(root);
while(!queue.isEmpty()) {
TreeNode node = queue.pollFirst();
if(record.contains(k - node.val)) {
return true;
}
record.add(node.val);
if(node.left != null) {
queue.offerLast(node.left);
}
if(node.right != null) {
queue.offerLast(node.right);
}
}
return false;
}
}
Idea 3. Store the ordered nums in array after inorder traversal, then two pointer scannning towards each other.
Time complexity: O(n)
Space complexity: O(h) + O(n)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private void inorderWalk(TreeNode root, List<Integer> nums) {
if(root == null) {
return;
} inorderWalk(root.left, nums);
nums.add(root.val);
inorderWalk(root.right, nums);
} public boolean findTarget(TreeNode root, int k) {
List<Integer> nums = new ArrayList<>(); inorderWalk(root, nums); for(int left = 0, right = nums.size()-1; left < right; ) {
int sum = nums.get(left) + nums.get(right);
if(sum == k) {
return true;
}
else if(sum < k) {
++left;
}
else {
--right;
}
} return false;
}
}
Idea 4. Inorder walk iterator + reversed inorder walk iterator to avoid extra space.
巧点: 1. 怎么停止循环?利用bst有序不重复,left < right; 否则 iter.hasNext()
2. 只有需要时才移动iterator
3. next() -> 遍历到下一个数就返回
Time complexity: O(n)
Space complexity: O(h)
import java.util.NoSuchElementException;
import java.lang.UnsupportedOperationException;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/ class InorderIterator implements Iterator<TreeNode> {
private TreeNode curr;
private Deque<TreeNode> stack;
private boolean forward; public InorderIterator(TreeNode root, boolean forward) {
this.curr = root;
this.stack = new ArrayDeque<>();
this.forward = forward;
} public boolean hasNext() {
return curr!= null || !stack.isEmpty();
} public TreeNode next() {
if(!hasNext()) {
throw new NoSuchElementException("tree run out of elements");
}
while(curr != null) {
stack.push(curr);
if(forward) {
curr = curr.left;
}
else {
curr = curr.right;
}
}
curr = stack.pop();
TreeNode prev = curr;
if(forward) {
curr = curr.right;
}
else {
curr = curr.left;
}
return prev;
} public void remove() {
throw new UnsupportedOperationException();
}
} class Solution {
public boolean findTarget(TreeNode root, int k) {
InorderIterator iter = new InorderIterator(root, true);
InorderIterator reversedIter = new InorderIterator(root, false); for(int left = iter.next().val, right = reversedIter.next().val; left < right;) {
if(left + right == k) {
return true;
}
else if(left + right < k) {
left = iter.next().val;
}
else {
right = reversedIter.next().val;
}
} return false;
}
}
import java.util.NoSuchElementException;
import java.lang.UnsupportedOperationException;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/ class InorderIterator implements Iterator<TreeNode> {
private TreeNode curr;
private Deque<TreeNode> stack;
private boolean forward; public InorderIterator(TreeNode root, boolean forward) {
this.curr = root;
this.stack = new ArrayDeque<>();
this.forward = forward;
} public boolean hasNext() {
return curr!= null || !stack.isEmpty();
} public TreeNode next() {
// if(!hasNext()) {
// throw new NoSuchElementException("tree run out of elements");
// }
while(curr != null || !stack.isEmpty()) {
if(curr != null) {
stack.push(curr);
if(forward) {
curr = curr.left;
}
else {
curr = curr.right;
}
}
else {
curr = stack.pop();
TreeNode prev = curr;
if(forward) {
curr = curr.right;
}
else {
curr = curr.left;
}
return prev;
}
}
throw new NoSuchElementException("tree run out of elements");
} public void remove() {
throw new UnsupportedOperationException();
}
} class Solution {
public boolean findTarget(TreeNode root, int k) {
InorderIterator forwardIter = new InorderIterator(root, true);
InorderIterator backwardIter = new InorderIterator(root, false); for(int left = forwardIter.next().val, right = backwardIter.next().val; left < right; ) {
int sum = left + right;
if(sum == k) {
return true;
}
else if (sum < k) {
left = forwardIter.next().val;
}
else {
right = backwardIter.next().val;
} } return false;
}
}
Two Sum IV - Input is a BST LT653的更多相关文章
- 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 653. 两数之和 IV - 输入 BST(Two Sum IV - Input is a BST)
653. 两数之和 IV - 输入 BST 653. Two Sum IV - Input is a BST 题目描述 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定 ...
- 【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] 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 ...
- 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 ...
- 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 ...
- [Swift]LeetCode653. 两数之和 IV - 输入 BST | 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 ...
随机推荐
- numpy--深度学习中的线代基础
参考自 微信公众号--深度学习世界(http://mp.weixin.qq.com/s?__biz=MzI4MDMwMDM3NA==&mid=2247484616&idx=1& ...
- Spring的一些资源
1.http://spring.io/ 2.http://projects.spring.io/spring-framework/
- VHS介绍
Java.JS HTTP流传输(VHS)介绍“我怎么才能让我的视频和Video.js一起玩?”“ 这是我们在使用Vio.js时最常见的问题之一.这是个好问题. 如果有人检查了Vo.js的拷贝,他们的内 ...
- centos搭建OPENldap
LDAP是轻量目录访问协议,英文全称是Lightweight Directory Access Protocol,一般都简称为LDAP.它是基于X.500标准的,但是简单多了并且可以根据需要定制.与X ...
- NumPy Ndarray 对象
NumPy Ndarray 对象 NumPy 最重要的一个特点是其 N 维数组对象 ndarray,它是一系列同类型数据的集合,以 0 下标为开始进行集合中元素的索引. ndarray 对象是用于存放 ...
- STL-stack和顺序栈实现括号匹配
2018-11-11-14:28:31 1.顺序栈 下面是我用数组实现的顺序栈,包含的函数有出入栈,查看栈顶元素,栈的大小,栈是否空等函数,当栈空间不够用时,对应的数组会自动增长. /******** ...
- Karma - MVC Framework for Unity3D
Karma is an MVC framework for Unity3D. Because of how Unity is structured, it actually turns out to ...
- [剑指Offer]34-二叉树中和为某一值的路径
题目链接 https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca?tpId=13&tqId=11177&t ...
- FortiGate设备管理
1.Web管理 1.FortiGate出厂配置 默认地址为192.168.1.99,可以通过https的方式进行web管理(默认用户名admin,密码为空).不同型号设备用于管理的接口略有不同,如: ...
- Delphi: TMethod转普通方法为对象方法
回看旧时代码,以往清楚之记忆渐渐模糊,事隔多年,遗忘正在发生. TMethod方法,当初熟练再看已陌生,再做复习以作备忘. 简言之,它做为一相桥接,将普通事件或方法转换为类方法,其多用于事件动态设置中 ...