[抄题]:

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

[暴力解法]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

以为用直接用helper函数就可以:dfs(root.left, k - root.val) || dfs(root.right, k - root.val);

但是这样做的问题是一定会把当前的root.val包括进去,然而结果其实可以不包括当前root节点的值

[一句话思路]:

任意取点时,把之前出现过的点先用hashset缓存一下。头一次见。

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

任意取点时,把之前出现过的点先用hashset缓存一下。头一次见。

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

哈希集合缓存

[关键模板化代码]:

DFS,但是要缓存

if(root == null)return false;
//exit: set contains k - root.val;
if (set.contains(k - root.val)) return true;
//store the root.val at present
set.add(root.val);
//expand to left, right
return dfs(root.left, set, k) || dfs(root.right, set, k);

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
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;
//exit: set contains k - root.val;
if (set.contains(k - root.val)) return true;
//store the root.val at present
set.add(root.val);
//expand to left, right
return dfs(root.left, set, k) || dfs(root.right, set, k);
}
}

最新文章

  1. 推荐一个winform 界面交互类库转
  2. python2与python3在windows下共存
  3. OpenGL显示图片
  4. cocos2d-x使用DragonBones动画
  5. easyui 常用代码
  6. malloc和free的区别
  7. CSS3 基础(1)——选择器详解
  8. &quot;《算法导论》之‘图’&quot;:最小生成树(无向图)
  9. 各类聚类(clustering)算法初探
  10. AS中jar包和aar包区别及导入导出
  11. 从使用角度看 ReentrantLock 和 Condition
  12. 批量提取图片主要3个颜色匹配中文名字并写入到excel设置对应颜色的背景
  13. [AngularJS] Angular 1.3 new $q constructor
  14. ORA-04030
  15. canvas学习笔记(下篇) -- canvas入门教程--保存状态/变形/旋转/缩放/矩阵变换/综合案例(星空/时钟/小球)
  16. Thinkpad个性化设置:F1~F12恢复正常按键,Fn与Ctrl按键互换
  17. poj2002 数正方形 (哈希+几何)
  18. (转)DNS解析过程详解
  19. loj2065 「SDOI2016」模式字符串
  20. 在命令行上启用 64 位 Visual C++ 工具集

热门文章

  1. if的用法
  2. MOSS 2013研究系列---列表的资源限制
  3. 读jQuery之二十(Deferred对象)--(转)
  4. JDK 9 &amp; JDK 10 新特性
  5. 问题排查-JVM堆外内存问题排查
  6. Python中的Bunch模式
  7. .NET单点登录实现方法----两种
  8. kubectl get pods The connection to the server was refused - did you specify the rig
  9. 将子类对象引用赋值给超类对象 JAVA 编译时多态性
  10. (文件名.JAVA)的文件名只能与该文件中的public类的名称一致