Sum Root to Leaf Numbers
来源:互联网 发布:网络金融理财咨询 编辑:程序博客网 时间:2024/06/06 12:45
题目描述:
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 number123
.
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
.
题目比较简单,就是找到叶子节点,记录中间经过的值,到根节点的时候加入到sum中。
代码如下:
public class Solution { int sum=0;public int sumNumbers(TreeNode root) {if(root==null)return 0;subSumNumbers(root, 0);return sum; }public void subSumNumbers(TreeNode root,int num){if(root.left==null&&root.right==null)sum+=num*10+root.val;if(root.left!=null)subSumNumbers(root.left, num*10+root.val);if(root.right!=null)subSumNumbers(root.right, num*10+root.val);}}
0 0
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- 排序--SelectSort优化
- C++拷贝构造函数详解
- servlet/action动态获取请求URL地址
- 同一Tomcat 多个端口部署不同的项目
- Lua入门教程 0.环境配置
- Sum Root to Leaf Numbers
- 分区管理的内存分配算法
- SVN 中trunk、tags、branches使用
- SDN benchmark -- Cbench最新安装说明
- 1076. Forwards on Weibo (30) PAT
- html学习笔记-2016-6-3 19:21:04
- Python循环语句for和while
- STL 算法
- Android Fragment 生命周期