Skip to content

Instantly share code, notes, and snippets.

@s4553711
Created April 29, 2018 06:37
Show Gist options
  • Save s4553711/75257ede2b843e124442732f367a8e02 to your computer and use it in GitHub Desktop.
Save s4553711/75257ede2b843e124442732f367a8e02 to your computer and use it in GitHub Desktop.
/**
* 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> nums;
inorder(root, nums);
int l = 0;
int r = nums.size() - 1;
while(l < r) {
int sum = nums[l] + nums[r];
if (sum == k) return true;
else if (sum < k)
++l;
else
--r;
}
return false;
}
private:
void inorder(TreeNode* root, vector<int>& nums) {
if (root == nullptr) return;
inorder(root->left, nums);
nums.push_back(root->val);
inorder(root->right, nums);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment