480.Binary Tree Paths
Last updated
Last updated
public List<String> binaryTreePaths(TreeNode root){
List<String> result=new ArrayList<String>();
if(root==null){
return result;
}
String path=String.valueOf(root.val);
dfs(root,path,result);
return result;
}
public void dfs(TreeNode root,String path,List<String> result){
if(root==null){
return;
}
if(root.left==null && root.right==null){
result.add(path);
return;
}
if(root.left!=null){
String newpath=path+"->"+String.valueOf(root.left.val);
dfs(root.left,newpath,result);
}
if(root.right!=null){
String newpath=path+"->"+String.valueOf(root.right.val);
dfs(root.right,newpath,result);
}
}