[leetcode]653. Two Sum IV - Input is a BST
Analysis
ummmm~—— [ummmm~]
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.
看到一句话,平生不识TwoSum,刷遍LeetCode也枉然~哈哈哈哈
用hash table(unordered_set)实现~
Implement
方法一(层序遍历)
/**
* 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:
bool findTarget(TreeNode* root, int k) {
if(!root)
return false;
unordered_set<int> num;
queue<TreeNode* > q;
q.push(root);
while(!q.empty()){
TreeNode* tmp = q.front();
q.pop();
if(num.count(k-tmp->val))
return true;
num.insert(tmp->val);
if(tmp->left)
q.push(tmp->left);
if(tmp->right)
q.push(tmp->right);
}
return false;
}
};
方法二(递归遍历)
/**
* 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:
bool findTarget(TreeNode* root, int k) {
if(!root)
return false;
unordered_set<int> num;
return traver(root, k, num);
}
bool traver(TreeNode* node, int k, unordered_set<int>& num){
if(!node)
return false;
if(num.count(k-node->val))
return true;
num.insert(node->val);
return traver(node->left, k, num)||traver(node->right, k, num);
}
};