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;
    }
};
相关推荐
Geektec几秒前
IMU 选型完全指南:从硬件参数到算法融合的系统工程视角
算法·imu·陀螺仪·加速度计·元器件选型
CQU_JIAKE5 分钟前
11.2【A】
算法
CoderYanger19 分钟前
Java EE 进阶:6.SpringBoot 配置文件(第二弹)
java·spring boot·spring·面试·职场和发展·java-ee·程序员创富
文丑颜不良啊21 分钟前
LeetCode1681~1700题目解析
java·leetcode
Godspeed Zhao1 小时前
从零开始学AI21——决策树
算法·决策树·机器学习
开开心心就好1 小时前
网页图片批量下载工具,输入链接就保存
服务器·算法·leetcode·支持向量机·pdf·ocr·1024程序员节
圣保罗的大教堂1 小时前
leetcode 462. 最小操作次数使数组元素相等 II 中等
leetcode
Navigator_Z2 小时前
LeetCode //C - 1313. Decompress Run-Length Encoded List
c语言·算法·leetcode
dialect_2 小时前
CODEFORCES ROUND 1127 DIV2
开发语言·c++·算法
Nuanyt3 小时前
LeetCode Hot 100 链表专题(四)· 3 题(Java)
java·算法·leetcode·链表·双指针