LintCode2016年算法比赛----二叉树的所有路径
2016-08-22 15:42
323 查看
二叉树的所有路径
题目描述给定一棵二叉树,找从根节点到叶子节点的所有路径
样例
给出下面这课二叉树:
1 / \ 2 3 \ 5
所有根到叶子的路径为:
[ "1->2->5", "1->3" ]
算法分析:
递归地处理二叉树,先将子树的所有路径求出,然后把根节点的数据贴到子路径的所有结果上
Java算法实现:
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root the root of the binary tree * @return all root-to-leaf paths */ public List<String> binaryTreePaths(TreeNode root) { // Write your code here List<String>list=new ArrayList<>(); if(root!=null){ List<String>left=binaryTreePaths(root.left); List<String>right=binaryTreePaths(root.right); String current=String.valueOf(root.val); if(left.size()==0&&right.size()==0){ list.add(current); } else{ if(left.size()!=0){ for(String leftStr:left){ list.add(current+"->"+leftStr); } } if(right.size()!=0){ for(String rightStr:right){ list.add(current+"->"+rightStr); } } } } return list; } }
相关文章推荐
- LintCode 二叉树的所有路径
- lintcode(480)——二叉树的所有路径
- 二叉树中路径和为某整数的所有路径 lint code by python
- lintcode----二叉树的所有路径
- LintCode-二叉树的所有路径
- LintCode2016年8月22日算法比赛----克隆二叉树
- lintcode binary-tree-paths 二叉树的所有路径
- lintcode:二叉树的所有路径
- lintcode binary-tree-maximum-path-sum 二叉树中的最大路径和
- lintcode&九章算法——No.70 二叉树的层次遍历(二) ? 待解决
- lintcode--二叉树中的最大路径和
- LintCode2016年8月22日算法比赛----将数组重新排序以构造最小值
- lintcode&九章算法——No.97 二叉树的最大深度 ? 待解决
- LintCode-二叉树中的最大路径和
- 算法题:lintcode#175 翻转二叉树(java)
- C++之求解二叉树中所有从根节点到叶节点的所有路径(23)---《那些奇怪的算法》
- Lintcode 376. 二叉树的路径和
- 二、lintcode刷题记录--二叉树的路径和
- LintCode2016年8月8日算法比赛----中序遍历和后序遍历构造二叉树
- lintcode:二叉树的路径和