public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<>();
if(root==null)
return list;
else
findpath(root,list,"");
return list;
}
public static void findpath(TreeNode root,List<String> list,String path){
String val = String.valueOf(root.val);
if(root.left!=null&root.right!=null){
path = path+val+"->";
findpath(root.left,list,path);
findpath(root.right,list,path);
}
else if(root.left==null&root.right!=null){
path = path+val+"->";
findpath(root.right,list,path);
}
else if(root.left!=null&root.right==null){
path = path+val+"->";
findpath(root.left,list,path);
}else
list.add(path+val);
}
采用递归的方式,分析每个节点是否有左右孩子,进行判断。