- Two Sum IV - Input is a BST
中文English
Given a binary search tree and a number n, find two numbers in the tree that sums up to n.
Example
Example1
Input:
{4,2,5,1,3}
3
Output: [1,2] (or [2,1])
Explanation:
binary search tree:
4
/
2 5
/
1 3
Example2
Input:
{4,2,5,1,3}
5
Output: [2,3] (or [3,2])
Notice
Without any extra space.
注意:这题要求不用extra space,所以不能保存inOrderTraversal的结果,也不能用set或map之类。
解法1:
一边inOrderTraversal一边BST查找,效率好像不是很高 (O(nlogn))?
代码如下:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param : the root of tree
* @param : the target sum
* @return: two number from tree witch sum is n
*/
vector<int> twoSum(TreeNode * root, int n) {
if (!root || n <= 0) return vector<int>();
origRoot = root;
inOrderTraversal(root, n);
return result;
}
private:
TreeNode * origRoot;
vector<int> result;
bool bst(TreeNode * root, int target) {
if (!root) return false;
if (root->val > target) return bst(root->left, target);
if (root->val < target) return bst(root->right, target);
return true;
}
void inOrderTraversal(TreeNode * root, int n) {
if (!root) return;
inOrderTraversal(root->left, n);
if (bst(origRoot, n - root->val)) result = vector<int>{root->val, n - root->val};
inOrderTraversal(root->right, n);
}
};
解法2:层次遍历+hashmap
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param : the root of tree
* @param : the target sum
* @return: two number from tree witch sum is n
*/
vector<int> twoSum(TreeNode * root, int n) {
if (!root) return {};
unordered_set<int> us;
queue<TreeNode *> q;
vector<int> res;
q.push(root);
us.insert(root->val);
while (!q.empty()) {
TreeNode *frontNode = q.front();
q.pop();
if (us.find(n - frontNode->val) != us.end()) {
return {frontNode->val, n - frontNode->val};
}
if (frontNode->left) {
q.push(frontNode->left);
us.insert(frontNode->left->val);
}
if (frontNode->right) {
q.push(frontNode->right);
us.insert(frontNode->right->val);
}
}
return {};
}
};