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"]
思路:就是普通的DFS
代码如下(已通过leetcode)
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list=new ArrayList<String>();
if(root==null) return list;
String s="";
DFS(root,s,list);
return list;
}
public void DFS(TreeNode root,String s,List<String> list) {
if(root.left==null && root.right==null) {
s=s+root.val;
list.add(s);
s="";
} else {
s=s+root.val+"->";
if(root.left!=null) {
DFS(root.left,s,list);
}
if(root.right!=null) {
DFS(root.right,s,list);
}
}
}
}