思路:题目需要记录从根节点开始走的路径,无疑选用前序遍历,用一个数组paths 记录走过的节点信息,遇到叶子节点就用另一个list记录下路径,回溯时删掉paths尾节点即可
java
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<>(); //处理的结果
if(root == null) {
return list;
}
List<Integer> paths = new ArrayList<>(); //当前路径顺序
func(root, paths, list);
return list;
}
public void func(TreeNode root, List<Integer> paths, List<String> list) {
//前序遍历,中
paths.add(root.val);
//如果是叶子节点,就记录下路径
if(root.left==null && root.right == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < paths.size()-1; i++) {
sb.append(paths.get(i)).append("->");
}
sb.append(paths.get(paths.size()-1));
list.add(sb.toString());
//return;
}
//左,不是叶子节点就一直递归深入
if(root.left != null) {
func(root.left, paths, list);
paths.remove(paths.size()-1);//结束一轮递归要回退一步
}
//右
if(root.right != null) {
func(root.right, paths, list);
paths.remove(paths.size()-1);
}
}
}