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的更多相关文章

  1. 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 ...

  2. LeetCode 653. 两数之和 IV - 输入 BST(Two Sum IV - Input is a BST)

    653. 两数之和 IV - 输入 BST 653. Two Sum IV - Input is a BST 题目描述 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定 ...

  3. 【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; 完

  4. [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 ...

  5. [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 ...

  6. 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 ...

  7. 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. 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 ...

  9. [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 ...

随机推荐

  1. Spring Cloud Ribbon Client

    首先,我们还是先从springcloud官方文档中找下相关说明,如下图所示,可以看到从1.2.0版本(也就是从Spriing Cloud Camden)之后,新增了这个通过配置文件来配置负载均衡的功能 ...

  2. python网络编程之进程论

    标签(空格分隔): 进程 什么是进程: 进程:正在进行的一个过程或者说一个任务.而负责执行任务则是cpu; 进程与程序的区别: 程序仅仅只是一堆代码而已,而进程指的是程序的运行过程 注意: 需要强调的 ...

  3. Swagger2

    参考文档:https://www.jianshu.com/p/5ae7267385b9 官网:https://swagger.io/ 注解参考:https://blog.csdn.net/weixin ...

  4. ELK 日志学习

    一.Elasticsearch 安装(所有的版本均使用5.5.0 ,且版需要相同 logstash \ kibana \ filebeat ) 官网下载地址:https://www.elastic.c ...

  5. Android学习路-Android Studio的工程目录

    说明:下图为一个app的工程目录,如果在res下随便建立文件夹(比如test等名字)是不会显示在工程内的

  6. 织梦 百度sitemap制作教程

    一.新建一个sitemap.htm模板 登录dedecms后台,选择[模板]-[模板管理]-[默认模板管理] 点击最下面的[新建模板]新建一个模板,并复制下面这段代码进去(将代码中的域名改为自己的): ...

  7. rancher2 挂载ceph-rbd

    一-创建ceph-secret.yml文件 RBD的KEY查看 ceph auth list 复制 client.admin 的key 并使用base64加密 创建ceph-secret.yml ku ...

  8. textarea 自动到右边就换行

    java 到最右边的时候自动换行如实例: textArea.setLineWrap(true);

  9. linux命令学习之:route

    我们在网络基础的时候谈过关于路由的问题,两台主机之间一定要有路由才能够互通TCP/IP的协议,否则就无法进行联机.一般来说,只要有网络接口,该接口就会产生一个路由,例如:eth0及lo. route命 ...

  10. gson所需jar包

    共需要四个jar包,分别为: gson-2.0.jar log4j-1.2.17.jar slf4j-api-1.7.10.jar slf4j-log4j12-1.7.10.jar 如果想要进行文件读 ...