sum-root-to-leaf-numbers(从根节点到叶子节点组成的值)

版权声明:本文为自学而写,如有错误还望指出,谢谢^-^ https://blog.csdn.net/weixin_43871369/article/details/89715609

题目描述

Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path1->2->3which represents the number123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \
  2   3

The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.

Return the sum = 12 + 13 =25.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode *root) {
        if(root==nullptr) return 0;
        int sum=0;
        return pre(root,sum);
    }
private:
    int pre(TreeNode *ptr,int sum)
    {
        if(ptr==nullptr) return 0;
        sum=ptr->val+sum*10;
        if(ptr->left==nullptr&&ptr->right==nullptr)
            return sum;
        return pre(ptr->left,sum)+pre(ptr->right,sum);
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43871369/article/details/89715609