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

这道题又是一道2sum的变种题,博主一直强调,平生不识TwoSum,刷尽LeetCode也枉然!只要是两数之和的题,一定要记得先尝试用HashSet来做,这道题只不过是把数组变成了一棵二叉树而已,换汤不换药,我们遍历二叉树就行,然后用一个HashSet,在递归函数函数中,如果node为空,返回false。如果k减去当前结点值在HashSet中存在,直接返回true;否则就将当前结点值加入HashSet,然后对左右子结点分别调用递归函数并且或起来返回即可,参见代码如下:

解法一:

class Solution {
public:
bool findTarget(TreeNode* root, int k) {
unordered_set<int> st;
return helper(root, k, st);
}
bool helper(TreeNode* node, int k, unordered_set<int>& st) {
if (!node) return false;
if (st.count(k - node->val)) return true;
st.insert(node->val);
return helper(node->left, k, st) || helper(node->right, k, st);
}
};

我们也可以用层序遍历来做,这样就是迭代的写法了,但是利用HashSet的精髓还是没变的,参见代码如下:

解法二:

class Solution {
public:
bool findTarget(TreeNode* root, int k) {
if (!root) return false;
unordered_set<int> st;
queue<TreeNode*> q{{root}};
while (!q.empty()) {
auto t = q.front(); q.pop();
if (st.count(k - t->val)) return true;
st.insert(t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
return false;
}
};

由于输入是一棵二叉搜索树,那么我们可以先用中序遍历得到一个有序数组,然后在有序数组中找两数之和就很简单了,直接用双指针进行遍历即可,参见代码如下:

解法三:

class Solution {
public:
bool findTarget(TreeNode* root, int k) {
vector<int> nums;
inorder(root, nums);
for (int i = , j = (int)nums.size() - ; i < j;) {
if (nums[i] + nums[j] == k) return true;
(nums[i] + nums[j] < k) ? ++i : --j;
}
return false;
}
void inorder(TreeNode* node, vector<int>& nums) {
if (!node) return;
inorder(node->left, nums);
nums.push_back(node->val);
inorder(node->right, nums);
}
};

类似题目:

Two Sum III - Data structure design

Two Sum II - Input array is sorted

Two Sum

参考资料:

https://leetcode.com/problems/two-sum-iv-input-is-a-bst/

https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/106090/my-c-python-solution

https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/106059/JavaC%2B%2B-Three-simple-methods-choose-one-you-like

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树的更多相关文章

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

  2. Leetcode653.Two Sum IV - Input is a BST两数之和4-输入BST

    给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true. struct TreeNode { int val; struct TreeNode * ...

  3. [LeetCode] 167. Two Sum II - Input array is sorted 两数和 II - 输入是有序的数组

    Given an array of integers that is already sorted in ascending order, find two numbers such that the ...

  4. [LeetCode] Two Sum II - Input array is sorted 两数之和之二 - 输入数组有序

    Given an array of integers that is already sorted in ascending order, find two numbers such that the ...

  5. 167 Two Sum II - Input array is sorted 两数之和 II - 输入有序数组

    给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数.函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2.请注意,返回的下标值(i ...

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

  7. 167. Two Sum II - Input array is sorted两数之和

    1. 原始题目 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数. 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2. 说明 ...

  8. 【leetcode 简单】第三十八题 两数之和 II - 输入有序数组

    给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数. 函数应该返回这两个下标值index1 和 index2,其中 index1 必须小于 index2. 说明: 返回的下标值( ...

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

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

随机推荐

  1. JSON解析的几种方式

    在开发中,网络请求和json解析使用的频率是一样高的,因为网络请求返回来的一般都是json(当然还有xml),这里讨论的是json,网络请求的工具类前面我的博客已经写过了,这里给出网址:http:// ...

  2. java.lang的详细解读

    软件包    java.lang 提供java编程语言实现程序设计的基础类 接口摘要 1> appendable  提供被添加char序列和值的对象 2>charSquence char值 ...

  3. SQL 数据库连续插入大批量数据时超时

    经常会处理大批量千万级的数据,一直以来都没问题.最近在处理时确出来了经常超时,程序跑一段时间就得停下来重启服务器,根据几次的调整发现了问题的所在,产生这类问题主要是以下几点所导致:      1.数据 ...

  4. 用SpringBoot搭建简单电商项目 01

    前几节呢,我们已经简单介绍了SpringBoot框架的使用,从这一节开始,我们尝试着使用SpringBoot框架来一步一步搭建一个简单电商项目.当然了,这不是真正的电商项目,你可以看成是一个CRUD案 ...

  5. Java基础学习笔记总结

    Java基础学习笔记一 Java介绍 Java基础学习笔记二 Java基础语法之变量.数据类型 Java基础学习笔记三 Java基础语法之流程控制语句.循环 Java基础学习笔记四 Java基础语法之 ...

  6. 【Nginx系列】Nginx编译与安装

    Nginx是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP代理服务器.Nginx是由Igor Sysoev为俄罗斯访问第二的Rambler.ru站点开发的. 一.Nginx ...

  7. Kettle 初始配置数据量类型资源库

    PS:有段时间不使用Kettle了,但总遇到小伙伴问起,写一篇记录下. 文档使用版本:KETTLE 7.0 Kettle资源库可分为文件与数据库,文件型只需要配置好存放路径就行,这边介绍的是配置数据库 ...

  8. Bate敏捷冲刺每日报告--day5

    1 团队介绍 团队组成: PM:齐爽爽(258) 小组成员:马帅(248),何健(267),蔡凯峰(285)  Git链接:https://github.com/WHUSE2017/C-team 2 ...

  9. Python 单向循环链表

    操作 is_empty() 判断链表是否为空 length() 返回链表的长度 travel() 遍历 add(item) 在头部添加一个节点 append(item) 在尾部添加一个节点 inser ...

  10. python的项目结构

    项目结构 知识点 创建项目,编写 __init__ 文件 使用 setuptools 模块,编写 setup.py 和 MANIFEST.in 文件 创建源文件的发布版本 项目注册&上传到 P ...