leetcode 653. Two Sum IV - Input is a BST

Posted いいえ敗者

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

遍历整颗bst,中序遍历可以得到一个有序的数组,这里可以用二分查找,也可以用map搞两个数的和,也可以用set边遍历边查找。

class Solution {
public:
    vector<int>v;
    void dfs(TreeNode * root) {
        if (root == NULL) return ;
        dfs(root->left);
        v.push_back(root->val);
        dfs(root->right);
    }
    bool findTarget(TreeNode* root, int k) {
        dfs(root);
        //cout << v.size() <<endl;
        map<int,int>mp;
        for (int i = 0; i < v.size(); ++i) {
            if (mp.count(k - v[i]) > 0) {
                return true;
            }
            mp[v[i]] = 1;
        }
        return false;
    }
};

 

class Solution {
private:
    unordered_set<int> uset;
public:
    bool findTarget(TreeNode* root, int k) {
        if (!root) return false;
        int val = root->val;
        if (uset.count(k-val)) return true;
        else {
            uset.insert(val);
            return findTarget(root->left, k) || findTarget(root->right, k);
        }
        return false;
    }
};

 

以上是关于leetcode 653. Two Sum IV - Input is a BST的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 653. Two Sum IV - Input is a BST

leetcode 653. Two Sum IV - Input is a BST

[Leetcode]653.Two Sum IV - Input is a BST

[Leetcode] Binary tree--653. Two Sum IV - Input is a BST

653. Two Sum IV - Input is a BST

LeetCode 653. Two Sum IV - Input is a BST(在BST中寻找两个节点,使它们的和为一个给定值)