653. Two Sum IV - Input is a BST

1.問題

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

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

Last updated