1. 程式人生 > >[LeetCode] Two Sum IV

[LeetCode] Two Sum IV

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

這道題又是一道2sum的變種題,博主一直強調,平生不識TwoSum,刷盡LeetCode也枉然!只要是兩數之和的題,一定要記得用雜湊表來做,這道題只不過是把陣列變成了一棵二叉樹而已,換湯不換藥,我們遍歷二叉樹就行,然後用一個雜湊set,在遞迴函式函式中,如果node為空,返回false。如果k減去當前結點值在雜湊set中存在,直接返回true;否則就將當前結點值加入雜湊set,然後對左右子結點分別呼叫遞迴函式並且或起來返回即可,參見程式碼如下:

解法一:

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

我們也可以用層序遍歷來做,這樣就是迭代的寫法了,但是利用雜湊表的精髓還是沒變的,參見程式碼如下:

解法二:

class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        if (!root) return false;
        unordered_set<int> s;
        queue<TreeNode*> q{{root}};
        while (!q.empty()) {
          auto t = q.front(); q.pop();
          if (s.count(k - t->val)) return true;
          s.insert(t->val);
          if (t->left) q.push(t->left);
          if (t->right) q.push(t->right);
        }
        return false;
    }
};

類似題目:

參考資料: