码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-03-26 01:22:25      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:一个   null   ==   tor   tco   NPU   val   cto   back   

题意:在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;
    }
};

  

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

标签:一个   null   ==   tor   tco   NPU   val   cto   back   

原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/12571732.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!