一:题目
二:上码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
/**
思路:1.前序遍历 (中 左 右 DFS)
2.递归算法(只考虑单层)
*/
public List<String> ans = new ArrayList<>();
public List<Integer> path = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
getAns(root);
return ans;
}
public void getAns(TreeNode root) {
path.add(root.val);
//确定终止条件 当遇见两个子节点都为空的时候 那么我们就是到达了 叶节点 那么路径就有了
//单个结点的为空的话 那么此时此时该该节点已经不在路径当中
if (root.left == null && root.right == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < path.size()-1; i++) {
sb.append(path.get(i)).append("->");
}
sb.append(path.get(path.size()-1));
ans.add(sb.toString());
return ;
}
//单层逻辑:
if (root.left != null) {//现在没有判空了 所以我们不遍历空结点 我们只遍历到叶节点
getAns(root.left);
path.remove(path.size()-1);//当我们结束一层递归的时候也就是我们找到一条路径
}
if (root.right != null) {
getAns(root.right);
path.remove(path.size()-1);
}
}
}