leetcode 653. Two Sum IV - Input is a BST
2017-08-07 10:30
483 查看
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:
Example 2:
遍历整颗bst,中序遍历可以得到一个有序的数组,这里可以用二分查找,也可以用map搞两个数的和,也可以用set边遍历边查找。
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
遍历整颗bst,中序遍历可以得到一个有序的数组,这里可以用二分查找,也可以用map搞两个数的和,也可以用set边遍历边查找。
class Solution { public: vector<int>v; void dfs(TreeNode * root) { if (root == NULL) return ; dfs(root->left); v.push_back(root->val); dfs(root->right); } bool findTarget(TreeNode* root, int k) { dfs(root); //cout << v.size() <<endl; map<int,int>mp; for (int i = 0; i < v.size(); ++i) { if (mp.count(k - v[i]) > 0) { return true; } mp[v[i]] = 1; } return false; } };
class Solution { private: unordered_set<int> uset; public: bool findTarget(TreeNode* root, int k) { if (!root) return false; int val = root->val; if (uset.count(k-val)) return true; else { uset.insert(val); return findTarget(root->left, k) || findTarget(root->right, k); } return false; } };
相关文章推荐
- leetcode 653. Two Sum IV - Input is a BST
- leetcode: 653. Two Sum IV - Input is a BST
- <easy>LeetCode Problem -- 653. Two Sum IV - Input is a BST
- LeetCode - 653. Two Sum IV - Input is a BST
- LeetCode653. Two Sum IV - Input is a BST
- leetcode 653. Two Sum IV - Input is a BST
- Leetcode 653. Two Sum IV - Input is a BST 两数相加4 解题报告
- LeetCode-653. Two Sum IV - Input is a BST
- python--leetcode653. Two Sum IV - Input is a BST
- leetcode 653. Two Sum IV - Input is a BST
- LeetCode-653. Two Sum IV - Input is a BST
- 2017.11.1 LeetCode - 653. Two Sum IV - Input is a BST
- Leetcode653. Two Sum IV - Input is a BST
- leetcode653. Two Sum IV - Input is a BST
- leetcode专题—653. Two Sum IV - Input is a BST
- Leetcode: 653. Two Sum IV - Input is a BST
- 【LeetCode】653. Two Sum IV - Input is a BST
- 【LeetCode】653. Two Sum IV - Input is a BST
- LeetCode 653. Two Sum IV – Input is a BST
- LeetCode - 653. Two Sum IV - Input is a BST