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 ...
随机推荐
- Oracle11g RAC安装
双节点RAC环境,数据库 racdb 实例1:racdb1 实例2:racdb2 1.IP规划 名称 oracle-db1 oracle-db2PUBLIC I ...
- PHP采集利器:Snoopy 试用心得
Snoopy.class.php下载 Snoopy是一个php类,用来模拟浏览器的功能,可以获取网页内容,发送表单.Snoopy正确运行需要你的服务器的PHP版本在4以上,并且支持PCRE(Perl ...
- cloudstack4.11+KVM+4网卡bond5+briage 交换机不作配置
网卡绑定配置 # cat ifcfg-em1TYPE=EthernetBOOTPROTO=noneDEVICE=em1ONBOOT=yesMASTER=bond0SLAVE=yes# cat ifcf ...
- cookie与webStorage区别
- [转]Docker到底是什么?为什么它这么火?
如果你是数据中心或云计算IT圈子的人,这一年多来应该一直在听到普通的容器.尤其是Docker,关于它们的新闻从未间断过.Docker1.0在今年6月发布后,声势更是达到了前所未有的程度. 动静之所以这 ...
- 2 c++对象被使用前要先被初始化
虽然有些时候int x;会被初始化为0,但是也可能不会,这就造成随机初始值会影响我们程序的运行. 类成员变量初始化顺序是依照其声明顺序而来的.基类要早于派生类别初始化. 构造函数最好使用成员初值列: ...
- Win7系统不能记忆窗口大小与位置解决方法
似在某此系统优化后,无意发现系统在注销或重启后,打开资源管理器,它以默认大小及位置显示. 对于习惯自定义操作来说,甚为不便,遍找方法未有奏效者,但总萦绕心头,时时记起. 今日再找问题解决方法,难兄难弟 ...
- cloud配置中心遇到的坑
https://blog.csdn.net/z960339491/article/details/80593982分布式配置中心为什么要有用分布式配置中心这玩意儿?现在这微服务大军已经覆盖了各种大小型 ...
- Nginx 做代理服务器时浏览器加载大文件失败 ERR_CONTENT_LENGTH_MISMATCH 的解决方案
此文章仅作为本人的笔记,文章转载自 http://blog.csdn.net/defonds/article/details/46042809 Nginx 做反向代理,后端是 tomcat,chro ...
- VIO回顾:从滤波和优化的视角
https://mp.weixin.qq.com/s/zpZERtWPKljWNAiASBLJxA 根据以上网页自己做的总结: 在机器人社区中,定位与构图问题属于状态估计问题.主流使用的工具可以对给定 ...