LeetCode 653. Two Sum IV - Input is a BST(在BST中寻找两个节点,使它们的和为一个给定值)

题意:在BST中寻找两个节点,使它们的和为一个给定值。

/**
 * 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:
    vector<int> v;
    void inorder(TreeNode* root){
        if(root == NULL) return;
        inorder(root -> left);
        v.push_back(root -> val);
        inorder(root -> right);
    }
    bool findTarget(TreeNode* root, int k) {
        if(root == NULL) return false;
        inorder(root);
        int len = v.size();
        int head = 0;
        int tail = len - 1;
        while(head < tail){
            int sum = v[head] + v[tail];
            if(sum == k) return true;
            else if(sum > k) --tail;
            else ++head;
        }
        return false;
    }
};

  

posted @ 2020-03-26 00:12  Somnuspoppy  阅读(131)  评论(0)    收藏  举报