Leetcode no. 257
2016-05-26 01:15
423 查看
257. Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
All root-to-leaf paths are:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res= new LinkedList<>();
if (root==null) return res;
search(root, "", res);
return res;
}
private void search(TreeNode root, String s, List<String> list){
if (root.left==null && root.right==null) list.add(s+root.val);
if (root.left!=null) search(root.left, s+root.val+"->", list);
if (root.right!=null) search(root.right, s+root.val+"->", list);
}
}
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"]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res= new LinkedList<>();
if (root==null) return res;
search(root, "", res);
return res;
}
private void search(TreeNode root, String s, List<String> list){
if (root.left==null && root.right==null) list.add(s+root.val);
if (root.left!=null) search(root.left, s+root.val+"->", list);
if (root.right!=null) search(root.right, s+root.val+"->", list);
}
}
相关文章推荐
- POJ 1008 (模拟)
- IntentFilter过滤规则
- Navicat
- Linux 网络 I/O 模型简介(图文)
- LeetCode 149. Max Points on a Line(直线上的点)
- 通过srvctl add命令添加database信息到srvctl管理器
- LeetCode 045 Jump Game II
- HTML文档设置标记
- LeetCode 150. Evaluate Reverse Polish Notation(计算后缀表达式)
- View事件分发机制
- expect 示例
- Android M InCallUI动画简析
- Base64编码与解码
- C++第六次作业
- LeetCode 151. Reverse Words in a String(反转单词)
- 数据挖掘之 时间序列分析
- LeetCode 152. Maximum Product Subarray(最大乘积)
- Android--Toast时间
- 初试Twitter API
- 2015年职级评定总结