LeetCode 653. Two Sum IV

来源:互联网 发布:永凯软件 编辑:程序博客网 时间:2024/05/16 10:23

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1:
Input:

    5   / \  3   6 / \   \2   4   7

Target = 9

Output: True
Example 2:
Input:

    5   / \  3   6 / \   \2   4   7

Target = 28

Output: False

知识点: 二分查找树的中序遍历是有序的。
注意: 可能有负数!!

/** * 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 fill_v(TreeNode* root)    {        if(!root)            return;        fill_v(root->left);        v.push_back(root->val);        fill_v(root->right);    }    bool findTarget(TreeNode* root, int k) {        fill_v(root);        int left = 0, right = v.size()-1;        while(left<right)        {            if(v[left]+v[right]>k)                right--;            else if(v[left]+v[right]<k)                left++;            else                return true;        }        return false;    }};
原创粉丝点击