leetcode --sum-root-to-leaf-numbers

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.


思路:本题可以按照先序遍历来求和,对于每个结点,采用 temp = value* 10 + node->val来更新值。注意先序遍历的写法,不要多考虑情况,一开始我加的判断太多了,其实根本不需要,只需要判断传入的Node是否为空即可!!而不需要预先做判断。

代码如下:

/**
 * 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;
        return sum(root,0);
    }
    int sum(TreeNode *root ,int value) {
        if(root == nullptr) 
            return 0;
        int temp = value * 10 + root->val;
        if(root->left == nullptr && root->right == nullptr) return temp;
        return sum(root->right,temp) + sum(root->left,temp);
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **Question: Given a binary tree containing digits from 0-...
    Richardo92阅读 452评论 1 2
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • 目录 简书的 markdown 都不支持 [TOC] 语法……我就不贴目录了。下面按照类别,列出了29道关于二叉树...
    被称为L的男人阅读 3,381评论 0 8
  • 当我们老了 岁月把我们的青丝 换成了白发 年轻飞扬的意气风发 换成了沉稳宁静 浓情蜜意刻画出 爱情的故事 牵手相伴...
    郭相麟阅读 196评论 0 0
  • 或许分离, 会是另一种回归。 回家的路途很近,坐趟刚开通的20分钟的地铁就可以到达当地的火车站,再坐趟一个半左右时...
    魔导阅读 260评论 3 0