[LeetCode] 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
這道題又是一道2sum的變種題,博主一直強調,平生不識TwoSum,刷盡LeetCode也枉然!只要是兩數之和的題,一定要記得用哈希表來做,這道題只不過是把數組變成了一棵二叉樹而已,換湯不換藥,我們遍歷二叉樹就行,然後用一個哈希set,在遞歸函數函數中,如果node為空,返回false。如果k減去當前結點值在哈希set中存在,直接返回true;否則就將當前結點值加入哈希set,然後對左右子結點分別調用遞歸函數並且或起來返回即可,參見代碼如下:
解法一:
class Solution { public: bool findTarget(TreeNode* root, intk) { 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; } };
類似題目:
Two Sum III - Data structure design
Two Sum II - Input array is sorted
Two Sum
參考資料:
https://discuss.leetcode.com/topic/98440/java-c-three-simple-methods-choose-one-you-like
https://discuss.leetcode.com/topic/100110/my-c-non-recursive-solution-using-unordered_set-and-stack
LeetCode All in One 題目講解匯總(持續更新中...)
[LeetCode] Two Sum IV - Input is a BST 兩數之和之四 - 輸入是二叉搜索樹