当前位置:网站首页>653. 两数之和 IV - 输入 BST
653. 两数之和 IV - 输入 BST
2022-04-23 09:04:00 【yitahutu79】
给定一个二叉搜索树 root 和一个目标结果 k,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。
示例 1:

输入: root = [5,3,6,2,4,null,7], k = 9
输出: true
示例 2:

输入: root = [5,3,6,2,4,null,7], k = 28
输出: false
提示:
二叉树的节点个数的范围是 [1, 104].
-104 <= Node.val <= 104
root 为二叉搜索树
-105 <= k <= 105
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
int count(struct TreeNode *root) {
if (root == NULL) return 0;
return count(root->left) + count(root->right) + 1;
}
void getItem(struct TreeNode *root, int *ret) {
if (root == NULL) return;
getItem(root->left, ret);
ret[++ret[0]] = root->val;
getItem(root->right, ret);
return ;
}
bool findTarget(struct TreeNode* root, int k){
int n = count(root);
int *ret = (int *)malloc(sizeof(int) * (n + 1));
ret[0] = 0;
getItem(root, ret);
int l = 1, r = ret[0];
while (l < r && ret[l] + ret[r] != k) {
if (ret[l] + ret[r] < k) l++;
else r--;
}
return l < r;
}
版权声明
本文为[yitahutu79]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_40713201/article/details/124357934
边栏推荐
- Find the sum of simple types of matrices
- MySQL小练习(仅适合初学者,非初学者勿进)
- 错误: 找不到或无法加载主类
- Star Trek强势来袭 开启元宇宙虚拟与现实的梦幻联动
- Single chip microcomputer nixie tube stopwatch
- Brief steps to build a website / application using flash and H5
- 关于堆的判断 (25 分) 两种插入方式
- GoLand debug go use - white record
- Arbre de dépendance de l'emballage des ressources
- node安装
猜你喜欢

Share the office and improve the settled experience

Valgrind and kcache grind use run analysis

Common errors of VMware building es8

请提前布局 Star Trek突破链游全新玩法,市场热度持续高涨

The K neighbors of each sample are obtained by packet switching

Star Trek强势来袭 开启元宇宙虚拟与现实的梦幻联动

LeetCode_ DFS_ Medium_ 1254. Count the number of closed islands

Enterprise wechat application authorization / silent login

资源打包关系依赖树

论文阅读《Multi-View Depth Estimation by Fusing Single-View Depth Probability with Multi-View Geometry》
随机推荐
Valgrind and kcache grind use run analysis
小程序报错 :should have url attribute when using navigateTo, redirectTo or switchTab
Group Backpack
What is augmented reality technology? Where can it be used?
Solidity 问题汇总
Go language self-study series | initialization of golang structure
MYCAT configuration
Production practice elk
根据后序和中序遍历输出先序遍历 (25 分)
调包求得每个样本的k个邻居
Bk3633 specification
L2-022 重排链表 (25 分)(map+结构体模拟)
基于ThinkPHP5版本TRC20-资金归集解决方案
Go language self-study series | golang method
基于点云凸包的凹包获取方法
玩转二叉树 (25 分)
还原二叉树 (25 分)
请提前布局 Star Trek突破链游全新玩法,市场热度持续高涨
爬虫使用xpath解析时返回为空,获取不到相应的元素的原因和解决办法
GoLand debug go use - white record