LintCode2016年算法比赛----二叉树的所有路径

二叉树的所有路径

题目描述

给定一棵二叉树,找从根节点到叶子节点的所有路径

样例

给出下面这课二叉树:

   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;
    }
    
}
posted on 2016-08-22 15:42  HorseShoe2016  阅读(946)  评论(0编辑  收藏  举报