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.
/**
* 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 searchKeyBST(struct TreeNode *root,int key) {
if(root == NULL){
return false;
}
//printf("key = %d,root->val = %d \n\r",key,root->val);
if(root->val == key){
return true;
}else if(key < root->val){
return searchKeyBST(root->left,key);
}else{
return searchKeyBST(root->right,key);
}
}
bool findTarget(TreeNode* root, int k) {
int key = 0;
queue<TreeNode *> qu;
if(root == NULL){
return false;
}
qu.push(root);
while(!qu.empty()){
TreeNode * node = qu.front();
key = k-(node->val);
if(key != node->val){
if(searchKeyBST(root,key)){
return true;
}
}
qu.pop();
if(node->left){
qu.push(node->left);
}
if(node->right){
qu.push(node->right);
}
}
return false;
}
};
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean searchKeyBST(TreeNode root,int key){
if(root == null){
return false;
}
if(key == root.val){
return true;
}else if(key < root.val){
return searchKeyBST(root.left,key);
}else{
return searchKeyBST(root.right,key);
}
}
public boolean findTarget(TreeNode root, int k) {
if(root == null){
return false;
}
Queue<TreeNode> qu = new LinkedList<TreeNode>();
qu.add(root);
while(qu.peek() != null){
TreeNode node = qu.poll();
int key = k - node.val;
if(key != node.val){
if(searchKeyBST(root,key)){
return true;
}
}
if(root.left != null){
qu.add(root.left);
}
if(root.right != null){
qu.add(root.right);
}
}
return false;
}
}