文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Two Sum IV - Input is a BST2. Solution
- Version 1
/**
* 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:
bool findTarget(TreeNode* root, int k) {
vector<int> numbers;
inorderTraverse(root, numbers);
for(int val : numbers) {
if(k - val == val) {
return false;
}
else if(search(root, k - val)) {
return true;
}
}
return false;
}
private:
void inorderTraverse(TreeNode* root, vector<int>& numbers) {
if(!root) {
return;
}
inorderTraverse(root->left, numbers);
numbers.push_back(root->val);
inorderTraverse(root->right, numbers);
}
bool search(TreeNode* root, int target) {
if(!root) {
return false;
}
if(root->val == target) {
return true;
}
else if(root->val > target) {
return search(root->left, target);
}
else {
return search(root->right, target);
}
}
};
- Version 2
/**
* 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:
bool findTarget(TreeNode* root, int k) {
return traverse(root, root, k);
}
private:
bool traverse(TreeNode* root, TreeNode* head, int k) {
if(root->left && traverse(root->left, head, k)) {
return true;
}
if(root->right && traverse(root->right, head, k)) {
return true;
}
if(k - root->val == root->val) {
return false;
}
return search(head, k - root->val);
}
bool search(TreeNode* root, int target) {
if(!root) {
return false;
}
if(root->val == target) {
return true;
}
else if(root->val > target) {
return search(root->left, target);
}
else {
return search(root->right, target);
}
}
};
网友评论