第一题是给了一棵树 打出所有从root到leave的路径
思路:递归DFS的方法,每次向两边孩子走,直到走到叶子节点为止。
public List<List<Integer>> res rightSideView(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
helper(root, res, new ArrayList<Integer>());
for (int i = 0; i < res.size(); i++) {
System.out.println(res.get(i));
}
return res;
}
private void helper(TreeNode root, List<List<Integer>> res, List<Integer> path) {
if (root.left == null && root.right == null) {
path.add(root.val);
res.add(new ArrayList<>(path));
path.remove(path.size() - 1);
return;
}
path.add(root.val);
if (root.left != null) helper(root.left, res, path);
if (root.right != null) helper(root.right, res, path);
path.remove(path.size() - 1);
return;
}