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;
    }
};
相关推荐
mmmmath_31 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z1 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
醇氧2 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法
大熊背3 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(二)
算法·白平衡·色度·色温
钓鱼的肝3 小时前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
参.商.3 小时前
【Day 53】76. 最小覆盖子串
leetcode·golang
HZZD_HZZD3 小时前
CSDN_批发市场水电漏损归因算法LAM的原理与落地
嵌入式硬件·物联网·算法
shirsl5 小时前
算法 Day 5 树 / 二叉树 + DFS
数据结构·python·算法
木子算法6 小时前
非凸、离散、还耦合:论文里的求解方法是一条四步流水线
人工智能·算法·目标跟踪