算法分析与设计——LeetCode Problem.653 Two Sum IV
来源:互联网 发布:材料预算软件 编辑:程序博客网 时间:2024/06/08 18:46
题目链接
问题描述
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 7Target = 9Output: True
Example 2:
Input: 5 / \ 3 6 / \ \2 4 7Target = 28Output: False
解题思路
可以将BST中序遍历一次,这样遍历的数据必是按升序排列,在遍历时将读到的数据存入vector中,然后用夹逼法得出结果即可。
(BST相关问题很多时候需要用到中序遍历)
class Solution {public:bool findTarget(TreeNode* root, int k) {if (root == NULL) {return false;}vector<int> v1;inorder(root, v1);int total = v1.size();int h = 0, t = total - 1;while (1) {if (h == t) return false;if (v1[h] + v1[t] == k) {return true;}if (v1[h] + v1[t] < k) {h++;continue;}if (v1[h] + v1[t] > k) {t--;continue;}}}private:void inorder(TreeNode *r, vector<int> &vec) {if (r != NULL) {inorder(r->left, vec);vec.push_back(r->val);inorder(r->right, vec);}}};
阅读全文
0 0
- 算法分析与设计——LeetCode Problem.653 Two Sum IV
- 算法分析与设计丨第一周丨 LeetCode(1)——Two Sum
- 算法分析与设计——LeetCode Problem.2 Add Two Numbers
- 算法分析与设计——LeetCode Problem.2 Add Two Numbers
- 算法分析与设计——LeetCode Problem.4 Median of Two Sorted Arrays
- 算法分析与设计——LeetCode Problem.16 3Sum Closest
- LeetCode #653 Two Sum IV
- 算法分析与设计week01——1.Two Sum
- 算法分析与设计课程15——377. Combination Sum IV
- leetcode[Two Sum IV
- LeetCode Two Sum IV
- leetcode Two Sum IV
- 算法设计Week1 LeetCode Algorithms Problem #1 Two Sum
- leetcode 653. Two Sum IV
- Leetcode 653. Two Sum IV
- 【LeetCode】653. Two Sum IV
- Leetcode 653. Two Sum IV
- 【LeetCode】653. Two Sum IV
- 基于UI响应时间的移动App性能测试解决方案
- 显式和隐式Intent
- css清除浮动的几种方法
- SVG常用元素标签列表
- LintCode 逆序对
- 算法分析与设计——LeetCode Problem.653 Two Sum IV
- GIT使用-1.GIT常见命令学习
- 位运算符归纳
- Matplotlib绘制动画
- Python操作excel文件
- 搭建Tomcat服务器环境
- 当面试官问你“你希望与什么样的上级共事?”如何回答?
- intelij maven生成web工程以及快速编译构建工程的方法
- C++基础(16)