aboutsummaryrefslogtreecommitdiff
path: root/two_sum_4.cpp
blob: c25bcc93b0a2b8ef4ff54f8a3a81c54ef7f45b8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "leetcode.h"

class Solution {
public:
  bool findTarget(TreeNode *root, int k) {
    vector<int> nums;
    order(root, nums);
    for (int i = 0, j = nums.size() - 1; i < j;) {
      if (nums[i] + nums[j] == k)
        return true;
      (nums[i] + nums[j] < k) ? i++ : j--;
    }
    return false;
  }

private:
  void order(TreeNode *root, vector<int> &nums) {
    if (root == NULL)
      return;
    order(root->left, nums);
    nums.push_back(root->val);
    order(root->right, nums);
  }
};