LeetCode - 129. Sum Root to Leaf Numbers

题目

LeetCode - 129. Sum Root to Leaf Numbers

题目链接

https://leetcode.com/problems/sum-root-to-leaf-numbers/

参考博客
解题思路
解题源码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sum = 0;
    void dfs(TreeNode* d, int num){
        if(!d) return ;
        if(!d->left && !d->right) sum += num;
        if (d->left) dfs(d->left, num * 10 + d->left->val);
        if (d->right) dfs(d->right, num * 10 + d->right->val);
    }
    int sumNumbers(TreeNode* root) {
        if (root) dfs(root, root->val);
        return sum;
    }
};

你可能感兴趣的:(LeetCode)