653. Two Sum IV - Input is a BST 二叉树版本
2024-09-04 16:34:09
[抄题]:
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);
}
}
最新文章
- 推荐一个winform 界面交互类库转
- python2与python3在windows下共存
- OpenGL显示图片
- cocos2d-x使用DragonBones动画
- easyui 常用代码
- malloc和free的区别
- CSS3 基础(1)——选择器详解
- ";《算法导论》之‘图’";:最小生成树(无向图)
- 各类聚类(clustering)算法初探
- AS中jar包和aar包区别及导入导出
- 从使用角度看 ReentrantLock 和 Condition
- 批量提取图片主要3个颜色匹配中文名字并写入到excel设置对应颜色的背景
- [AngularJS] Angular 1.3 new $q constructor
- ORA-04030
- canvas学习笔记(下篇) -- canvas入门教程--保存状态/变形/旋转/缩放/矩阵变换/综合案例(星空/时钟/小球)
- Thinkpad个性化设置:F1~F12恢复正常按键,Fn与Ctrl按键互换
- poj2002 数正方形 (哈希+几何)
- (转)DNS解析过程详解
- loj2065 「SDOI2016」模式字符串
- 在命令行上启用 64 位 Visual C++ 工具集
热门文章
- if的用法
- MOSS 2013研究系列---列表的资源限制
- 读jQuery之二十(Deferred对象)--(转)
- JDK 9 &; JDK 10 新特性
- 问题排查-JVM堆外内存问题排查
- Python中的Bunch模式
- .NET单点登录实现方法----两种
- kubectl get pods The connection to the server was refused - did you specify the rig
- 将子类对象引用赋值给超类对象 JAVA 编译时多态性
- (文件名.JAVA)的文件名只能与该文件中的public类的名称一致