Middle-题目46:129. Sum Root to Leaf Numbers

原创 2016年05月31日 16:06:28

题目原文:
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,

    1
   / \
  2   3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.
题目大意:
有一个二叉树,节点是0-9构成的数字,这样从根节点到叶子节点的每一条路径构成一个数,计算所有路径上的数的和。
题目分析:
本题就是一个记忆化的前序遍历,一直记录着前面的数,每次向孩子搜索的时候把当前数×10加上当前节点的数,搜到叶子节点的时候加到当前的和里面。
源码:(language:java)

public class Solution {
    private int currentTotal = 0;
    public int sumNumbers(TreeNode root) {
       dfs(root,0);
       return currentTotal;
    }
    private void dfs(TreeNode node, int currentSum) {
        if(node == null)
            return;
        else if(isLeaf(node)) {
            currentSum+=node.val;
            currentTotal+=currentSum;
        }
        else {
            currentSum+=node.val;
            dfs(node.left,currentSum*10);
            dfs(node.right,currentSum*10);
        }
    }
    private boolean isLeaf(TreeNode node) {
        return node.left==null && node.right==null;
    }
}

成绩:
1ms,beats 28.93%,众数1ms,60.87%

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

LeetCode:129. Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a numb...

leetcode129. Sum Root to Leaf Numbers

129. Sum Root to Leaf NumbersGiven a binary tree containing digits from 0-9 only, each root-to-leaf ...

LeetCode129 Sum Root to Leaf Numbers

详细见:leetcode.com/problems/sum-root-to-leaf-numbers Java Solution: github package leetcode; ...

LeetCode: Sum Root to Leaf Numbers [129]

【题目】 Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a ...

Leetcode-129. Sum Root to Leaf Numbers

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN...

Leetcode[129]-Sum Root to Leaf Numbers

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

Sum Root to Leaf Numbers - LeetCode 129

题目描述: Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a...

leetcode_129_Sum Root to Leaf Numbers

思路: 和pathsum系列是一个思路,后序遍历至某个节点,将root-to-leaf的所有结点的值表示成一个数和sum相加,直至遍历完所有的leaf结点,返回sum。

Leetcode 129. Sum Root to Leaf Numbers (Medium) (cpp)

Leetcode 129. Sum Root to Leaf Numbers (Medium) (cpp)

[leetcode] #129 Sum Root to Leaf Numbers

1.题目 Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)