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也枉然!只要是兩數之和的題,一定要記得先嘗試用HashSet來做,這道題只不過是把數組變成了一棵二叉樹而已,換湯不換葯,我們遍歷二叉樹就行,然后用一個HashSet,在遞歸函數函數中,如果node為空,返回false。如果k減去當前結點值在HashSet中存在,直接返回true;否則就將當前結點值加入HashSet,然后對左右子結點分別調用遞歸函數並且或起來返回即可,參見代碼如下:
解法一:
class Solution { public: bool findTarget(TreeNode* root, int k) { unordered_set<int> st; return helper(root, k, st); } bool helper(TreeNode* node, int k, unordered_set<int>& st) { if (!node) return false; if (st.count(k - node->val)) return true; st.insert(node->val); return helper(node->left, k, st) || helper(node->right, k, st); } };
我們也可以用層序遍歷來做,這樣就是迭代的寫法了,但是利用HashSet的精髓還是沒變的,參見代碼如下:
解法二:
class Solution { public: bool findTarget(TreeNode* root, int k) { if (!root) return false; unordered_set<int> st; queue<TreeNode*> q{{root}}; while (!q.empty()) { auto t = q.front(); q.pop(); if (st.count(k - t->val)) return true; st.insert(t->val); if (t->left) q.push(t->left); if (t->right) q.push(t->right); } return false; } };
由於輸入是一棵二叉搜索樹,那么我們可以先用中序遍歷得到一個有序數組,然后在有序數組中找兩數之和就很簡單了,直接用雙指針進行遍歷即可,參見代碼如下:
解法三:
class Solution { public: bool findTarget(TreeNode* root, int k) { vector<int> nums; inorder(root, nums); for (int i = 0, j = (int)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* node, vector<int>& nums) { if (!node) return; inorder(node->left, nums); nums.push_back(node->val); inorder(node->right, nums); } };
類似題目:
Two Sum III - Data structure design
Two Sum II - Input array is sorted
參考資料:
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/106090/my-c-python-solution