Two Sum IV - Input is a BST

知乎三面的一道题

653. Two Sum IV - Input is a BST

 方法一:hash

使用哈希表来保存BST中节点的值。每当我们将新节点的值插入哈希表时,我们都会检查哈希表是否包含k-node.val

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

方法二: 中序遍历转换为有序数组

通过使用中序遍历来保存BST中节点的值。然后,我们使用两个指针,从数组的开头和结尾开始,找出是否有总和k

class Solution {
public:
 bool findTarget(TreeNode* root, int k) {
        vector<int> nums;
        inorder(root, nums);
        for(int i = 0, j = nums.size()-1; i<j;){
            if(nums[i] + nums[j] == k)return true;
            (nums[i] + nums[j] < k)? i++ : j--;
        }
        return false;
    }
    
    void inorder(TreeNode* root, vector<int>& nums){
        if(root == NULL)return;
        inorder(root->left, nums);
        nums.push_back(root->val);
        inorder(root->right, nums);
    }
};

方法三: 二分

对于每个节点,我们检查k - node.val在BST中是否存在。

class Solution{
public:
    bool findTarget(TreeNode* root, int k) {
        return dfs(root, root,  k);
    }
    
    bool dfs(TreeNode* root,  TreeNode* cur, int k){
        if(cur == NULL)return false;
        return search(root, cur, k - cur->val) || dfs(root, cur->left, k) || dfs(root, cur->right, k);
    }
    
    bool search(TreeNode* root, TreeNode *cur, int value){
        if(root == NULL)return false;
        return (root->val == value) && (root != cur) 
            || (root->val < value) && search(root->right, cur, value) 
                || (root->val > value) && search(root->left, cur, value);
    }
};

猜你喜欢

转载自blog.csdn.net/behboyhiex/article/details/82819026
今日推荐