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 a
2016-05-19 14:34
387 查看
class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { public int sumNumbers(TreeNode root) { if(root==null)return 0; return sumRoot(root,0); } private int sumRoot(TreeNode root, int sum) { if(root==null)return 0; sum=sum*10+root.val;//关键 if(root.left==null&&root.right==null)return sum; return sumRoot(root.left, sum)+sumRoot(root.right, sum);//左右都要递归哦 } }
相关文章推荐
- xcode7 解决NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9843)
- maven打好的jar包如何在运行时指定main-class
- 【leetcode】11. Container With Most Water
- [Ogre][地形][原创]基于OgreTerrain的地形实现
- 人工智能基础01--绪论
- LeetCode 11. Container With Most Water(容器装水)
- RAD Studio 10 安装失败 提示错误 License status check failure解决办法
- leetcode 11. Container With Most Water
- 使用 SDL 过程中遇到的两个问题: 找不到main函数 和 链接错误
- ansible 报错 FAILED | rc=0 >> MODULE FAILURE 解决方法
- codeforces 675E E. Trains and Statistic(线段树+dp)
- 问题解决了,可是为什么呢?could not find the main class.program will exitmain
- hdu 2476 String Painter
- UVa-442-Matrix Chain Multiplication
- ORA-01122: database file 4 failed verification check
- HDU 1848 —— Fibonacci again and again 【博弈 sg函数】
- HDU 2746 ——String painter
- uva 253 Cube painting
- LightOj--1071--Baker Vai(拆点最大费用流)
- HDU 1023 Train Problem II (卡特兰数)未解决未解决未解决未解决