653. Two Sum IV

来源:互联网 发布:机顶盒mac地址绑定 编辑:程序博客网 时间:2024/05/22 00:25

题目:

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   7Target = 9Output: True

Example 2:

Input:     5   / \  3   6 / \   \2   4   7Target = 28Output: False
思路:

本题,先利用先序遍历将结点值存储在数组里,再用find函数查找(k-当前结点)是否存在

代码:

/** * 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> res;    bool findTarget(TreeNode* root, int k) {           Preorder(root);        for(int i=0;i<res.size();i++)        {            int temp =k - res[i];            if(find(res.begin(),res.end(),temp)!=res.begin()+i&&find(res.begin(),res.end(),temp)!=res.end())                return true;        }        return false;    }private:void Preorder(TreeNode* root){    if(root!=NULL)    {        res.push_back(root->val);        Preorder(root->left);        Preorder(root->right);    }    }};


原创粉丝点击