当前位置:网站首页>Sword finger offer II 056. Sum of two nodes in a binary search tree (simple binary search tree DFS hash table double pointer iterator)
Sword finger offer II 056. Sum of two nodes in a binary search tree (simple binary search tree DFS hash table double pointer iterator)
2022-07-28 22:20:00 【Calm in the wind and rain】
The finger of the sword Offer II 056. The sum of two nodes in a binary search tree
Given a binary search tree The root node root And an integer k , Please judge whether there are two nodes in the binary search tree, and the sum of their values is equal to k . Suppose that the values of nodes in the binary search tree are unique .
Example 1:
Input : root = [8,6,10,5,7,9,11], k = 12
Output : true
explain : node 5 And nodes 7 The sum is equal to 12
Example 2:
Input : root = [8,6,10,5,7,9,11], k = 22
Output : false
explain : There are no two nodes. The sum of the values is 22 The node of
Tips :
The range of the number of nodes in a binary tree is [1, 104].
-104 <= Node.val <= 104
root For binary search tree
-105 <= k <= 105
source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/opLdQZ
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
analysis
Method 1 :dfs + Hashtable ( Spatial complexity O(n))
Directly traverse the storage node value to find whether there are two numbers that meet the conditions .
Method 2 : iterator + Double pointer ( Spatial complexity O(h)
h It's the depth of the tree . Refer to the first 6 The train of thought of the question and the 55 Iterator of question :
https://blog.csdn.net/weixin_43942435/article/details/122953885
https://blog.csdn.net/weixin_43942435/article/details/124128125
Treat the binary search tree as an array , Create two opposite iterators , So there are two pointers , Refer to the first 6 The train of thought of the question can be .
Answer key (Java)
Method 1 :dfs + Hashtable
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */
class Solution {
private Set<Integer> set = new HashSet<>();
public boolean findTarget(TreeNode root, int k) {
if (root == null) {
return false;
}
if (set.contains(k - root.val)) {
return true;
}
set.add(root.val);
boolean left = findTarget(root.left, k);
boolean right = findTarget(root.right, k);
return left || right;
}
}
Method 2 : iterator + Double pointer
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */
class Solution {
public boolean findTarget(TreeNode root, int k) {
if (root == null) {
return false;
}
BSTIterator iterNext = new BSTIterator(root);
BSTIteratorReversed iterPrev = new BSTIteratorReversed(root);
int next = iterNext.next();
int prev = iterPrev.prev();
while (next != prev) {
if (next + prev == k) {
return true;
}
if (next + prev < k) {
next = iterNext.next();
} else {
prev = iterPrev.prev();
}
}
return false;
}
public class BSTIterator {
private TreeNode root;
private Deque<TreeNode> stack;
public BSTIterator(TreeNode root) {
this.root = root;
stack = new LinkedList<>();
}
public int next() {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
int val = root.val;
root = root.right;
return val;
}
public boolean hasNext() {
return root != null || !stack.isEmpty();
}
}
public class BSTIteratorReversed {
private TreeNode root;
private Deque<TreeNode> stack;
public BSTIteratorReversed(TreeNode root) {
this.root = root;
stack = new LinkedList<>();
}
public int prev() {
while (root != null) {
stack.push(root);
root = root.right;
}
root = stack.pop();
int val = root.val;
root = root.left;
return val;
}
public boolean hasPrev() {
return root != null || !stack.isEmpty();
}
}
}
边栏推荐
- Add DNS server to LAN for domain name resolution
- 90. Subset II
- HCIP(8)
- 成立不到一年!MIT衍生量子计算公司完成900万美元融资
- Data visualization news, different forms of news reports
- Hcip experiment (15)
- Aimbetter insight into your database, DPM and APM solutions
- 为什么 0.1 + 0.2 不等于0.3?如何解决这个问题?
- tutorial/detailed_workflow.ipynb 量化金融Qlib库
- 迪赛智慧数——折线图(堆叠面积图):2022年不同职业人群存款额占月收入比例排名
猜你喜欢

From Web3 to web2.5, is it backward or another way?

熊市下 DeFi 的未来趋势

SQL injection less42 (post stack injection)
![[LiteratureReview]Object Detection and Mapping with Bounding Box Constraints](/img/37/7cb5fa3a9078a5f5947485147c819d.png)
[LiteratureReview]Object Detection and Mapping with Bounding Box Constraints

Lin Xiaobin, head of Tencent cloud database, borrowed 100 million yuan to speculate in stocks? Insider: the amount is not true

Desai wisdom number - line chart (stacking area chart): ranking of deposits of different occupational groups in the proportion of monthly income in 2022
![[CS231N]Lecture_ 2:Image Classification pipelin](/img/4f/de56b071560ada746c587a9dbc5f02.jpg)
[CS231N]Lecture_ 2:Image Classification pipelin

什么是时间复杂度

成立不到一年!MIT衍生量子计算公司完成900万美元融资

Embrace open source guidelines
随机推荐
Principle of object. Prototype. ToString. Call()
腾讯云数据库负责人借了一亿元炒股?知情人士:金额不实
第 7 篇:绘制旋转立方体
Basic introduction of Rockwell AB PLC rslogix digital quantity IO module
Tensorflow serving high performance machine learning model service system
display 各值的区别
Hcip seventh experiment
LCR测试仪最为主要的功能和用途都是什么
gprs网络指的是什么
拥抱开源指南
HCIP(15)
CDN working principle
Have you seen the management area decoupling architecture? Can help customers solve big problems
[cloud native kubernetes] mapping external service under kubernetes cluster eendpoint
Establishment of Ruiji takeout development environment
HCIP(8)
SQL注入 Less34(POST型宽字节注入+布尔盲注)
Apifox: satisfy all your fantasies about API
[machine learning] naive Bayesian classification of text -- Classification of people's names and countries
Oracle triggers