# 653. Two Sum IV - Input is a BST

## 1.問題

* 判斷樹中任意兩束的總和是否等於k

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LKMccB6vrgTQPA9S6hh%2F-LKMdCVSHhaA3K91ieBI%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-08-20%20%E4%B8%8B%E5%8D%8810.02.14.png?alt=media\&token=73317fb7-2639-44d2-b6fb-9302f6033099)

## 2.想法

## 3.程式碼

```
/**
 * 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> v;
        getList(root, v);
        for (int i = 0; i < v.size(); i++) {
            for (int j = i + 1; j < v.size(); j++) {
                if (v[i] + v[j] == k) {
                    return true;
                }
            }    
        }
        return false;
    }
private:
    void getList(TreeNode* root, vector<int>& v) {
        if (root) {
            if (root->left){
                getList(root->left, v);
            }
            v.push_back(root->val);
            if (root->right){
                getList(root->right, v);
            }
        }
    }
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LKMccB6vrgTQPA9S6hh%2F-LKMdO3p0jT9jFqijxQL%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-08-20%20%E4%B8%8B%E5%8D%8810.02.56.png?alt=media\&token=887804d0-884e-4038-8812-3c18d35fd59c)
