sum-root-to-left-numbers

版权声明:版权归作者所有,转发请标明 https://blog.csdn.net/weixin_40087851/article/details/82014856

题目简述

  • 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.

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

  • The root-to-leaf path1->3represents the number13.
  • Return the sum = 12 + 13 =25.

    这里写图片描述

  • 翻译:给定一个包含从0到9的数字的二叉树,每个根到叶的路径可以表示一个数字。例如,根到叶子路径1-> 2-> 3,它代表数字123。找到所有根到叶子数字的总和。root-to-leaf path1-> 2表示数字12。root-to-leaf path1-> 3表示数字13。返回总和= 12 + 13 = 25。

分析

  • 观察从根到叶子的数字,我们发现均是先访问当前节点,再访问左右节点。因此我们利用前序遍历来求解题目。

  • 假设我们当前已经利用前序遍历到达了叶子节点,分两种情况讨论:
    这里写图片描述

  • 我们使用变量res记录最终的总和,使用str记录当前的数字(字符串)。

代码段

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:

    void calc(TreeNode *root,int& res,string str){
        if(root==nullptr){
            return;
        }
        str+=to_string(root->val);
        if(root->left==nullptr && root->right==nullptr){
            res+=stoi(str);
            return;
        }
        calc(root->left,res,str);
        calc(root->right,res,str);
    }

    int sumNumbers(TreeNode *root) {
        if(root==nullptr)
            return 0;
        int res=0;
        string str="";
        calc(root,res,str);
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_40087851/article/details/82014856