[leetcode-257]Binary Tree Paths(java)
2015-08-24 13:18
281 查看
问题描述:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
[“1->2->5”, “1->3”]
分析:使用递归的思想,且递归到叶节点时终止,即root.left==null && root.right == null时。
代码如下:304ms
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
[“1->2->5”, “1->3”]
分析:使用递归的思想,且递归到叶节点时终止,即root.left==null && root.right == null时。
代码如下:304ms
[code]/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private void findPath(List<String> res,String tmp,TreeNode root){ if(root==null) return; if(root.left==null && root.right==null){ res.add(tmp+Integer.toString(root.val)); return; } findPath(res,tmp+Integer.toString(root.val)+"->",root.left); findPath(res,tmp+Integer.toString(root.val)+"->",root.right); } public List<String> binaryTreePaths(TreeNode root) { List<String> res = new LinkedList<>(); if(root==null) return res; findPath(res,"",root); return res; } }
相关文章推荐
- spring配置jedisPool
- Missing artifact javax.jms:jms:jar: Missing artifact com.sun.jdmk Missing artifact com.sun.jmx:jmxri
- 【Developer Log】Java的内存使用、垃圾回收和内存泄漏
- Spring事务的隔离级别
- java中的IO操作总结(四)
- java中的IO操作总结(三)
- java中的IO操作总结(二)
- Spring Security : limit login attempts example
- Java反射api详解
- Java中的迭代器模式
- eclipse 运行MapReduce程序错误异常汇总(解决Map not fount)
- MyEclipse8.5中SVN的安装方法
- java quartz的使用,做时间轮询调用 CronTrigger
- JSON转javabean(pojo)利器
- Java之旅hibernate(7)——数据加载get和load
- Java OCR tesseract 图像智能字符识别技术 Java代码实现
- Java OCR tesseract 图像智能字符识别技术
- Java转义字符
- java--空字符串""和null的区别
- Java中文图像识别tesseract-ocr || tif