博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
129. Sum Root to Leaf Numbers
阅读量:4550 次
发布时间:2019-06-08

本文共 1824 字,大约阅读时间需要 6 分钟。

题目:

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.

 

Hide Tags

链接:  

6/8/2017

3ms, 9%

很长时间想不起来怎么做,把tree想成graph就搞定了

注意

1. 第22行还是要加上叶结点的值

2. 第25,32行需要加上当前节点的值,然后删掉。

1 public class Solution { 2     public int sumNumbers(TreeNode root) { 3         if (root == null) { 4             return 0; 5         } 6         List
ret = new ArrayList
(); 7 List
list = new ArrayList
(); 8 dfs(root, ret, list); 9 int sum = 0;10 for (int i = 0; i < ret.size(); i++) {11 sum += ret.get(i);12 }13 return sum;14 }15 private void dfs(TreeNode root, List
ret, List
list) {16 if (root.left == null && root.right == null) {17 int number = 0;18 for (int i = 0; i < list.size(); i++) {19 number = number * 10 + list.get(i);20 }21 number = number * 10 + root.val;22 ret.add(number);23 return;24 }25 list.add(root.val);26 if (root.left != null) {27 dfs(root.left, ret, list);28 }29 if (root.right != null) {30 dfs(root.right, ret, list);31 }32 list.remove(list.size() - 1);33 }34 }

别人更简单的做法:

1 public int sumNumbers(TreeNode root) {2     return sum(root, 0);3 }4 5 public int sum(TreeNode n, int s){6     if (n == null) return 0;7     if (n.right == null && n.left == null) return s*10 + n.val;8     return sum(n.left, s*10 + n.val) + sum(n.right, s*10 + n.val);9 }

更多讨论

转载于:https://www.cnblogs.com/panini/p/6970021.html

你可能感兴趣的文章
python 一些特殊用法和坑
查看>>
WIFI密码破解全攻略
查看>>
c++string各种函数
查看>>
errno.h含义
查看>>
字典树(模型体)
查看>>
盒模型详解
查看>>
bzoj2157 旅游
查看>>
bzoj5016 [Snoi2017]一个简单的询问
查看>>
poj2417 bzoj3239 Discrete Logging(bsgs)
查看>>
UVa10054 - The Necklace(欧拉回路【输出带来的麻烦)
查看>>
string和stringbuffer的区别 集合的作用 ArrayList vector linklist hashmap hashtable collection和collections...
查看>>
6月27日 ajax
查看>>
iOS开发之画图板(贝塞尔曲线)
查看>>
4嵌入式作业io
查看>>
IntelliJ Idea编译报错:javacTask: 源发行版 1.7 需要目标发行版 1.7
查看>>
Cognos中新建SQLserver数据源的步骤
查看>>
HttpClient连接超时及读取超时
查看>>
SQL优化方法
查看>>
SEO必须掌握的高级搜索指令
查看>>
生产者消费者模型
查看>>