LeetCode - Easy - 191. Number of 1 Bits
阿新 • • 發佈:2020-12-24
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/two-sum-bsts
- 查詢兩棵二叉搜尋樹之和
給出兩棵二叉搜尋樹,請你從兩棵樹中各找出一個節點,使得這兩個節點的值之和等於目標值 Target。
如果可以找到返回 True,否則返回 False。
示例 1:
輸入:root1 = [2,1,4], root2 = [1,0,3], target = 5
輸出:true
解釋:2 加 3 和為 5 。
思路:
- 遍歷二叉樹,獲取所有val,此處採用前序遍歷;
- 對獲取到的值按從小到大進行排序;
- 邊界判斷,對不可能的情況直接返回false;
- 利用二分查詢法lower_bound查詢第一個大於等於目標值的位置,如果其值正好是另一半則返回true;
- 注意二分查詢函式的常用用法:
/*lower_bound(val):返回容器中第一個值【大於或等於】val的元素的iterator位置。
upper_bound(val): 返回容器中第一個值【大於】val的元素的iterator位置。
當查詢成功時,迭代器指向找到的元素;反之,如果查詢失敗,迭代器的指向和 last 迭代器相同。
常用方法:idx = lower_bound(out.begin(), out.end(), other) - out.begin();
如果查詢失敗,idx值為out.size();否則idx為合法值!
out[idx] = …
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
static bool Cmp(const int& a, const int& b)
{
return a < b;
}
void GetElements(TreeNode* root, vector<int>& out)
{
if (root == nullptr) {
return;
}
out.push_back(root->val);
GetElements (root->left, out);
GetElements(root->right, out);
}
bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) {
if (root1 == nullptr || root2 == nullptr) {
return false;
}
vector<int> out1;
vector<int> out2;
GetElements(root1, out1);
GetElements(root2, out2);
sort(out1.begin(), out1.end(), Cmp);
sort(out2.begin(), out2.end(), Cmp);
int m = out1.size();
int n = out2.size();
if (out1[0] + out2[0] > target) {
return false;
}
if (out1[m - 1] + out2[ n - 1] < target) {
return false;
}
for (int i = 0; i < m; i++) {
int other = target - out1[i];
int idx = lower_bound(out2.begin(), out2.end(), other) - out2.begin();
if (idx < 0 || idx >= n) {
continue;
}
if (out2[idx] == other) {
return true;
}
}
return false;
}
};