【LeetCode】653. Two Sum IV

来源:互联网 发布:java 字符串补位 编辑:程序博客网 时间:2024/05/16 12:00

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。

方法1:直接递归查找。

class Solution {public:    map<int,bool> mp;    bool findTarget(TreeNode* root, int k) {        if(root==NULL)            return false;        if(mp[k-root->val])return true;        else{            mp[root->val]=true;            return findTarget(root->left,k)||findTarget(root->right,k);        }    }};

方法2:先通过DFS遍历二叉树,把数字存放在一个VECTOR里面,然后再查找。

class Solution {public:    map<int,bool> mp;    vector<int> vec;    void DFS(TreeNode* root){        if(root==NULL)return;        DFS(root->left);        vec.push_back(root->val);        DFS(root->right);    }    bool findTarget(TreeNode* root, int k) {       DFS(root);       for(int i=0;i<vec.size();i++){           if(mp[k-vec[i]]){               return true;           }           mp[vec[i]]=true;       }        return false;    }};
原创粉丝点击