Home => ProblemSet => 7.1-04:sum-root-to-leaf-numbers
Problem1406--7.1-04:sum-root-to-leaf-numbers

1406: 7.1-04:sum-root-to-leaf-numbers

Time Limit: 1 Sec  Memory Limit: 128 MB  Submit: 0  Solved: 0
[ Submit ] [ Status ] [ Creator: ][ 参考程序 ]

Description

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.
给你一个二叉树的根节点 root ,树中每个节点都存放有一个 0 到 9 之间的数字。
每条从根节点到叶节点的路径都代表一个数字:

例如,从根节点到叶节点的路径 1 -> 2 -> 3 表示数字 123 。
计算从根节点到叶节点生成的 所有数字之和 。

叶节点 是指没有子节点的节点。


Input

第一行一个整数n,表示接下来将输入的数的个数
第二行n个数,空格分隔,表示一棵二叉树,-1表示非结点

Output

一个整数

Sample Input Copy

3
1 2 3

Sample Output Copy

25

HINT

样例一解释:
从根到叶子节点路径1->2代表数字12从根到叶子节点路径1->3代表数字13因此,数字总和 = 12 + 13 =25


样例二:

输入:
5
4 9 0 5 1
输出:
1026
解释:
从根到叶子节点路径 4->9->5 代表数字 495
从根到叶子节点路径 4->9->1 代表数字 491
从根到叶子节点路径 4->0 代表数字 40
因此,数字总和 = 495 + 491 + 40 = 1026




  • 树中节点的数目在范围 [1, 1000] 内
  • 0 <= Node.val <= 9
  • 树的深度不超过 10


Source/Category