653. Two Sum IV - Input is a BST*

653. Two Sum IV - Input is a BST*

https://leetcode.com/problems/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

C++ 实现 1

前序遍历二分搜索树, 用哈希表保存结果, 最后参照 1. Two Sum* 求解.

class Solution {
private:
    void dfs(TreeNode *root, unordered_set<int> &record) {
        if (!root)
            return;

        record.insert(root->val);
        dfs(root->left, record);
        dfs(root->right, record);
    }
public:
    bool findTarget(TreeNode* root, int k) {
        unordered_set<int> record;
        dfs(root, record);

        for (auto &val : record)
            if (record.count(k - val) && (k - val) != val)
                return true;
        return false;
    }
};

C++ 实现 2

二分搜索树的中序遍历得到的结果是有序的, 然后参考 167. *Two Sum II - Input array is sorted 利用对撞指针求解.

class Solution {
private:
    void InOrder(TreeNode *root, vector<int> &record) {
        if (!root)
            return;

        InOrder(root->left, record);
        record.push_back(root->val);
        InOrder(root->right, record);
    }

public:
    bool findTarget(TreeNode* root, int k) {
        vector<int> record;
        InOrder(root, record);
        // 然后使用 Two Sum
        int l = 0, r = record.size() - 1;
        while (l < r) {
            if (record[l] + record[r] == k)
                return true;
            else if (record[l] + record[r] < k)
                l ++;
            else
                r --;
        }
        return false;
    }
};
发布了327 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104490349
今日推荐