一:题目
二:上码
class Solution {
public List ans = new ArrayList<>();
public List path = new ArrayList<>();
public List 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);
}
}
}