zoukankan      html  css  js  c++  java
  • LeetCode——sum-root-to-leaf-numbers

    Question

    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.

    Solution

    递归遍历,到叶子节点就累加起来,然后需要用一个变量来记录路径中的值。

    Code

    class Solution {
    public:
        int sumNumbers(TreeNode *root) {
            int total = 0;
            string path;
            sumNumbersCore(root, path, total);
            return total;
        }
        void sumNumbersCore(TreeNode* root, string path, int& total) {
            if (root != NULL) {
                // int 转 char
                path.push_back('0' + root->val);
                if (root->left != NULL)
                	sumNumbersCore(root->left, path, total);
                if (root->right != NULL)
                	sumNumbersCore(root->right, path, total);
                if (root->left == NULL && root->right == NULL) {
               		total += stoi(path);
            		path.pop_back();
                }
            }
        }
    };
    
  • 相关阅读:
    P2519 [HAOI2011]problem a
    P1084 疫情控制
    P1941 飞扬的小鸟
    NOIP填坑计划
    P2831 愤怒的小鸟
    AGC 16 D
    P3960 列队
    Python3爬虫相关软件,库的安装
    软件理论基础—— 第一章命题逻辑系统L
    软件理论基础——导论
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7081580.html
Copyright © 2011-2022 走看看