二叉树的所有路径(简单)
2020年6月8日
题目来源:力扣
解题
- 递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
if(root==null) return new ArrayList<String>();
List<String> list=new ArrayList<>();
DFS(root,"",list);
return list;
}
public void DFS(TreeNode root,String path,List<String> list){
if(root!=null){
path+=Integer.toString(root.val);
if(root.left==null && root.right==null){
list.add(path);
}
else{
path+="->";
DFS(root.left,path,list);
DFS(root.right,path,list);
}
}
}
}