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();
                }
            }
        }
    };
    
  • 相关阅读:
    Live2d Test Env
    Live2d Test Env
    Live2d Test Env
    Live2d Test Env
    Live2d Test Env
    偷东西的学问-背包问题
    HMM-前向后向算法理解与实现(python)
    详解数组分段和最大值最小问题(最小m段和问题)
    打家劫舍系列
    面试题56
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7081580.html
Copyright © 2011-2022 走看看