leetcode129. Sum Root to Leaf Numbers
来源:互联网 发布:unity3d 中wintext 编辑:程序博客网 时间:2024/05/16 08:51
129. Sum Root to Leaf Numbers
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 3The 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.
解法一
递归遍历每一条从根节点到叶子结点的路径,并根据路径存成对应的值,如123,把这些值放到list列表中,最后进行遍历,求和。
/** * 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) { List<Integer> list = new ArrayList<Integer>(); int s = 0; if (root == null) { return 0; } helper(root, s, list); int sum = 0; for (int i = 0; i < list.size(); i++) { sum += list.get(i); } return sum; } public void helper(TreeNode root, int s, List<Integer> list) { if (root == null) { return; } s = s * 10 + root.val; if (root.left == null && root.right == null) { list.add(s); s = (s - root.val) / 10; return; } helper(root.left, s, list); helper(root.right, s, list); s = (s - root.val) / 10; }}
解法二
dfs,递归,将左右子树的完整路径加起来。
/** * 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; } return sum(root, 0); } public int sum(TreeNode root, int sum) { if (root == null) { return 0; } if (root.left == null && root.right == null) { return sum * 10 + root.val; } return sum(root.left, sum * 10 + root.val) + sum (root.right, sum * 10 + root.val); }}
阅读全文
0 0
- leetcode129---Sum Root to Leaf Numbers
- LeetCode129 Sum Root to Leaf Numbers
- LeetCode129—Sum Root to Leaf Numbers
- [LeetCode129] Sum Root to Leaf Numbers
- [LeetCode129]Sum Root to Leaf Numbers
- LeetCode129. Sum Root to Leaf Numbers
- LeetCode129 Sum Root to Leaf Numbers
- leetcode129. Sum Root to Leaf Numbers
- leetcode129~Sum Root to Leaf Numbers Add to List
- leetcode129 Sum Root to Leaf Numbers java 算法
- 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
- tomcat
- CodeForces
- Fragment实现底部功能栏
- Andriod 常用控件,TextView ,EditText之登录框demo
- MySQL 技术内幕:InnoDB存储引擎pdf
- leetcode129. Sum Root to Leaf Numbers
- Android环境搭建
- MXNet的运算符-Part1
- 基于单链表、环形队列(并发有锁)的多线程生产者消费者模型
- 安卓-环境搭建
- 云计算架构技术与实践pdf
- 在线云评测系统日志七
- 用带缓存的I/O操作写文件粘贴
- Vue学习——v-for