LCR 056. 两数之和 IV - 输入二叉搜索树

文章目录

题意

题目链接

思路

代码

C++ 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void tree2vetor(TreeNode *root, vector<int> &num) {
        if (root == NULL) {
            return ;
        }
        tree2vetor(root->left, num);
        num.push_back(root->val);
        tree2vetor(root->right, num);
    }
    bool findTarget(TreeNode* root, int k) {
        vector<int> num;
        tree2vetor(root, num);
        int l = 0, r = num.size() - 1 ;
        while (l < r)
        {
            const int tmp = num[l] + num[r];
            if (tmp == k)
                return true;
            if (tmp > k)
                r--;
            else 
                l++;
        }
        return false;
    }
};
相关推荐
方案开发PCBA抄板芯片解密19 小时前
什么是算法:高效解决问题的逻辑框架
算法
songx_9919 小时前
leetcode9(跳跃游戏)
数据结构·算法·游戏
小白狮ww20 小时前
RStudio 教程:以抑郁量表测评数据分析为例
人工智能·算法·机器学习
AAA修煤气灶刘哥20 小时前
接口又被冲崩了?Sentinel 这 4 种限流算法,帮你守住后端『流量安全阀』
后端·算法·spring cloud
kk”21 小时前
C语言快速排序
数据结构·算法·排序算法
纪元A梦21 小时前
贪心算法应用:基因编辑靶点选择问题详解
算法·贪心算法
3壹21 小时前
数据结构精讲:栈与队列实战指南
c语言·开发语言·数据结构·c++·算法
skytier21 小时前
Construct内报错和定位解决
算法
skytier21 小时前
Ascend print数据落盘使用
算法
etcix1 天前
dmenux.c: integrate dmenu project as one file
c语言·前端·算法