问题 easy
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
分析
- 这是LeetCode 44周竞赛题第一题,难度easy。
- 需要对树进行遍历,并在遍历过程中完成一些操作。
- 一开始首先想到的是递归法,很简单直接,虽然速度有点慢,但不失为一种不错的方法。
- 后来学到一种迭代法来遍历树,这种解题模版能解很多二叉树相关问题,套进来试试,果然不错。
- 参考: 98. Validate Binary Search Tree.md
- 参考:Learn one iterative inorder traversal, apply it to multiple tree questions
代码
/*
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
//方法一:递归法 遍历树,速度奇慢
unordered_map<int,int> map;
bool findTarget(TreeNode* root, int k) {
if(root == NULL) return false;
if(root)
{
map[root->val] = 1;
int targetToFind = k - root->val;
if((targetToFind != root->val) && map.find(targetToFind) != map.end()) return true;
}
if(root->left && findTarget(root->left,k)) return true;
if(root->right && findTarget(root->right,k)) return true;
return false;
}
//使用 迭代法 遍历树,速度很快,35ms,排名进入第一根柱子
bool findTarget(TreeNode* root, int k) {
unordered_map<int,int> map;
stack<TreeNode*> stack;
int targetToFind;
while(root || !stack.empty())
{
while(root)
{
stack.push(root);
root = root->left;
}
root = stack.top();
targetToFind = k - root->val;
if(map.find(targetToFind) != map.end()) return true;
map[root->val] = 1;
root = root->right;
stack.pop(); //容易漏,一旦漏了,stack永不为空,死循环
}
return false;
}
//使用 迭代法 遍历树,将上述的unordered_map(没必要)换成set,32ms
bool findTarget(TreeNode* root, int k) {
set<int> iset;
stack<TreeNode*> stack;
int targetToFind;
while(root || !stack.empty())
{
while(root)
{
stack.push(root);
root = root->left;
}
root = stack.top();
targetToFind = k - root->val;
if(iset.find(targetToFind) != iset.end()) return true;
iset.insert(root->val);
root = root->right;
stack.pop(); //容易漏,一旦漏了,stack永不为空,死循环
}
return false;
}
};