leetcode 129 求根节点到叶节点数字之和

一、题目描述

二、解题思路

可以采用递归的思想来解决这个问题。

三、代码实现

cpp 复制代码
/**
 * 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:
    int sumNumbers(TreeNode* root) {
        return dfs(root,0);
    }

    int dfs(TreeNode* root,int presum){
        presum=presum*10+root->val;
        //递归出口(叶子结点)
        if(root->left==nullptr&&root->right==nullptr) return presum;
        int ret=0;
        //处理左子树
        if(root->left) ret+=dfs(root->left,presum);
        //处理右子树
        if(root->right) ret+=dfs(root->right,presum);
        return ret;
    }
};
相关推荐
Kt&Rs21 分钟前
11.9 LeetCode 题目汇总与解题思路
算法·leetcode
ゞ 正在缓冲99%…42 分钟前
leetcode1547.切棍子的最小成本
数据结构·算法·leetcode·动态规划
海盗猫鸥43 分钟前
「C++」vector的使用及接口模拟详解
开发语言·c++
2401_841495641 小时前
【LeetCode刷题】移动零
数据结构·python·算法·leetcode·数组·双指针法·移动零
开心星人1 小时前
Leetcode hot100 Java刷题(二)
java·算法·leetcode
liulilittle2 小时前
CPU亲和性深度实践:从基础原理到Intel大小核架构优化
c++·线程·进程·cpu·量化·高频·亲核性
hn小菜鸡2 小时前
LeetCode 153.寻找旋转排序数组中的最小值
数据结构·算法·leetcode
Albert Edison2 小时前
【项目设计】基于正倒排索引的Boost搜索引擎
linux·网络·c++·后端·http·搜索引擎
DeniuHe2 小时前
逻辑回归(Logistic Regression)详细解释与公式推导
算法·机器学习·逻辑回归
迅量科技资讯分享2 小时前
手机拍照明晰度评估:传感器尺寸像素数量与处理器算法解析
算法·三星·像素