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;
    }
};
相关推荐
vortex511 分钟前
几种 dump hash 方式对比分析
算法·哈希算法
Wei&Yan1 小时前
数据结构——顺序表(静/动态代码实现)
数据结构·c++·算法·visual studio code
团子的二进制世界2 小时前
G1垃圾收集器是如何工作的?
java·jvm·算法
吃杠碰小鸡2 小时前
高中数学-数列-导数证明
前端·数学·算法
故事不长丨2 小时前
C#线程同步:lock、Monitor、Mutex原理+用法+实战全解析
开发语言·算法·c#
long3162 小时前
Aho-Corasick 模式搜索算法
java·数据结构·spring boot·后端·算法·排序算法
近津薪荼2 小时前
dfs专题4——二叉树的深搜(验证二叉搜索树)
c++·学习·算法·深度优先
熊文豪2 小时前
探索CANN ops-nn:高性能哈希算子技术解读
算法·哈希算法·cann
熊猫_豆豆2 小时前
YOLOP车道检测
人工智能·python·算法
艾莉丝努力练剑3 小时前
【Linux:文件】Ext系列文件系统(初阶)
大数据·linux·运维·服务器·c++·人工智能·算法