653. Two Sum IV
来源:互联网 发布:有道云笔记数据恢复 编辑:程序博客网 时间:2024/05/21 17:24
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
用了最蠢的办法把节点先全部保存起来,再循环找到和为k的点
之前一直在用树递归写,思路大致是每个节点上先将k减去当前节点的val,然后再遍历当前节点的左右子树,相当于在bst树上进行查找值为k-val的点,一旦找到就返回true,但是一直没写对,,再看看。
class Solution {
public:
bool findTarget(struct TreeNode* root, int k)
{
vector<int> temp;
int i,j;
inorder(root,temp);
for(i=0;i<temp.size();i++){
for(j=i+1;j<temp.size();j++){
if(temp[i]+temp[j]==k) return true;
}
}
return false;
}
void inorder(struct TreeNode* root,vector<int>& temp)
{
if(root==NULL) return;
temp.push_back(root->val);
inorder(root->left,temp);
inorder(root->right,temp);
}
};
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 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
- leetcode 653. Two Sum IV
- leetcode 653. Two Sum IV
- linux内核模块编译
- Spark 自带demo学习日志
- [!] /usr/bin/git clone https://github.com/CocoaPods/Specs.git master --progress Cloning into 'master
- LeetCode
- 实现一个单例模式的类,要求线程安全
- 653. Two Sum IV
- PAT_A 1048. Find Coins (25)
- Oracle高级优化——侵入存储提纲(用PRIVATE OUTLINE)
- Java中的Null是什么?
- 《MySQL入门很简单》学习笔记(7)之第7章索引(关键词:数据库/MySQL/索引/设计索引/创建索引/删除索引)
- Hadoop-Invert-Index
- CodeForces 339 A.Helpful Maths(水~)
- android studio 解决依赖库冲突问题
- PAT 1064. Complete Binary Search Tree (30) 快速建立完全二叉树