Created
April 29, 2018 06:37
-
-
Save s4553711/75257ede2b843e124442732f367a8e02 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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