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

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

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

/**
 * 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 sum = 0;
    void track_back(TreeNode* cur , string s)
    {
        if(cur == nullptr ) return;
        s += to_string(cur->val);
        if(cur->left == nullptr && cur->right ==nullptr) sum += stoi(s);
        track_back(cur->left , s);
        track_back(cur->right ,s);
        return;
    }
    int sumNumbers(TreeNode* root) {
        string s;
        track_back(root,s);
        return sum;
    }
};
相关文章
|
3天前
【Leetcode 2487】从链表中移除节点 —— 单调栈
解题思路:维持一个单调递增栈,当栈为空时,记录当前节点为头节点;否则当前节点为栈顶节点的后继节点
|
3天前
leetcode-SQL-608. 树节点
leetcode-SQL-608. 树节点
18 0
LeetCode | 面试题 02.02. 返回倒数第 k 个节点
LeetCode | 面试题 02.02. 返回倒数第 k 个节点
|
3天前
leetcode代码记录(完全二叉树的节点个数
leetcode代码记录(完全二叉树的节点个数
8 1
|
3天前
leetcode2487.从链表中移除节点
leetcode2487.从链表中移除节点
20 1
|
3天前
|
C语言
【C语言】Leetcode 876. 链表的中间节点
【C语言】Leetcode 876. 链表的中间节点
19 0
|
3天前
|
Java
LeetCode题解- 两两交换链表中的节点-Java
两两交换链表中的节点-Java
14 0
|
3天前
leetcode-6134:找到离给定两个节点最近的节点
leetcode-6134:找到离给定两个节点最近的节点
18 0
|
3天前
|
Go
golang力扣leetcode 2049.统计最高分的节点数目
golang力扣leetcode 2049.统计最高分的节点数目
19 0
|
3天前
leetcode-1791:找出星型图的中心节点
leetcode-1791:找出星型图的中心节点
20 0
leetcode-1791:找出星型图的中心节点