[LeetCode]129. Sum Root to Leaf Numbers
2016-03-17 10:29
363 查看
Given a binary tree containing digits from
a number.
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 =
思路:采用深度优先搜索的方法,每搜索到一个点,就更新自身的值
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.
思路:采用深度优先搜索的方法,每搜索到一个点,就更新自身的值
/** * 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 = 0; Stack<TreeNode> s = new Stack<TreeNode>(); TreeNode temp = new TreeNode(0); s.push(root); while(s.isEmpty() == false) { temp = s.pop(); if(temp.left == null && temp.right == null) { res = res + temp.val; } if(temp.right != null) { temp.right.val = temp.right.val + temp.val*10; s.push(temp.right); } if(temp.left != null) { temp.left.val = temp.left.val + temp.val*10; s.push(temp.left); } } return res; } }
相关文章推荐
- iOS应用崩溃日志分析
- 敏捷测试驱动模式-项目质量保障体系
- linux /sys目录下各个子目录的具体说明
- Redis安装配置
- python网络爬虫入门(二)———模拟登陆知乎
- JDK安装和配置环境
- Betta
- Java内部类、本地类、匿名类、文件类解读
- 解析posix与perl标准的正则表达式区别
- C语言-结构体
- 查找一个字符串出现最多,并计算其次数
- tomcat集群中实现Session共享
- Python引用模块和查找模块路径
- 【ESP8266】使用ESP8266 NONOS SDK的JSON API
- bootstrap常用功能快速入门以及常见问题解决方案
- test
- 由IOS上编译Lame引起的一些事情
- <permission>和<uses-permission>
- 【windows多线程】原子操作 Interlocked系列函数
- Java面向对象:封装、继承、多态