LeetCode Sum Root to Leaf Numbers
2015-09-07 22:29
260 查看
原题链接在这里:https://leetcode.com/problems/sum-root-to-leaf-numbers/
Given a binary tree containing digits from
An example is the root-to-leaf path
Find the total sum of all root-to-leaf numbers.
For example,
The root-to-leaf path
The root-to-leaf path
Return the sum = 12 + 13 =
本题与Path Sum II相似。
DFS, 终止条件都是左右child都是空,否则cur*10加child.val, 递归调用函数,回来时除以10.
Note:1. helper 是pass by value, 所以res一定要用个array存储。
2. 递归调用后需要去掉尾节点,本题中除以10即可。
3. root == null 的corner case 是在主函数里单独讨论, dfs里不需要重复讨论。
Time Complexity: O(n). Space: O(h), h是树的高度.
AC Java:
Given a binary tree containing digits from
0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path
1->2->3which 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->2represents the number
12.
The root-to-leaf path
1->3represents the number
13.
Return the sum = 12 + 13 =
25.
本题与Path Sum II相似。
DFS, 终止条件都是左右child都是空,否则cur*10加child.val, 递归调用函数,回来时除以10.
Note:1. helper 是pass by value, 所以res一定要用个array存储。
2. 递归调用后需要去掉尾节点,本题中除以10即可。
3. root == null 的corner case 是在主函数里单独讨论, dfs里不需要重复讨论。
Time Complexity: O(n). Space: O(h), h是树的高度.
AC Java:
/** * Definition for a binary tree node. * public 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; } int [] res = new int[1]; int cur = root.val; dfs(root, cur, res); return res[0]; } private void dfs(TreeNode root, int cur, int [] res){ if(root.left == null && root.right == null){ res[0] += cur; return; } if(root.left != null){ cur = cur*10 + root.left.val; dfs(root.left, cur, res); cur /= 10; } if(root.right != null){ cur = cur*10 + root.right.val; dfs(root.right, cur, res); cur /= 10; } } }
相关文章推荐
- 学习 《一步步搭建自己的博客》 第一版 之异常 边理解边记录
- Objective-C( Category 分类,非正式协议,分类延展)
- 数据库连接和定义
- 欢迎使用CSDN-markdown编辑器
- Qt 信号槽机制解析一 理论篇
- HDOJ 1010 Tempter of the Bone
- 简单工厂、工厂方法、抽象工厂的区别
- Swift实现的快速排序及sorted方法的对比
- Android - 模块添加与编译
- URL cache
- uva 129 困难的串
- 【搜集】队列和栈的功能相互转换
- linux 下查看硬盘坏道代码(转)
- 安卓简单开发(1)----环境搭建
- 数据库连接
- USB Audio accessory设备
- 1181 变形课
- 白化
- 顺序表
- scala学习之模式匹配