DFS
访问一个节点则添加进去,直到访问到叶子节点,将答案添加进结果集
套路:
1.边界条件
2.满足条件
3.搜索
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> ans = new ArrayList<>();
public void robot(TreeNode root,String str){
//边界条件
if(root==null) return;
str=str+root.val;
//满足条件
if(root.left==null && root.right==null){
ans.add(str);
}
//搜索
if(root.left!=null)
robot(root.left,str+"->");
if(root.right!=null)
robot(root.right,str+"->");
}
public List<String> binaryTreePaths(TreeNode root) {
robot(root,"");
return ans;
}
}