LeetCode 653. Two Sum IV – Input is a BST

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
/**
 * 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:
    void dfs(TreeNode* root){
         if(root==NULL) return;
         nums.push_back(root->val);
         checked[root->val]++;
         dfs(root->left);
         dfs(root->right);
    }
    bool findTarget(TreeNode* root, int k) {
         dfs(root);
         for(int i=0;i<nums.size();i++)
             if(k-nums[i]!=nums[i]&&checked[k-nums[i]]>=1)
                return true;
             else if(k-nums[i]==nums[i]&&checked[nums[i]]>=2)
                return true;
         return false;
    }
private:
    vector<int> nums;
    map<int,int> checked;
};
posted @ 2018-12-06 22:11  A-Little-Nut  阅读(101)  评论(0编辑  收藏  举报