给定一个二叉树,返回所有从根节点到叶子节点的路径。

    说明: 叶子节点是指没有子节点的节点。

    示例:
    输入:

    1
    / \
    2 3
    \
    5

    输出: [“1->2->5”, “1->3”]

    解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/binary-tree-paths


    思路:
    树的dfs算法相对图的dfs算法更容易理解一点,BFS也是树比较好理解
    这里先看官方给的定义
    /*
    Definition for a binary tree node.
    public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
    }
    */
    每个节点都有他的左孩子或者右孩子,除非他是叶子节点
    所以遍历就看是不是叶子节点就行了,不是叶子节点就递归,是叶子节点就记录该条路径,回溯

    1. class Solution {
    2. public static LinkedList<String> dfs(TreeNode root, String way, LinkedList<String>path){
    3. if (root == null){
    4. return null;
    5. }else {
    6. //路径中加入该节点
    7. way += Integer.toString(root.val);
    8. // 当前节点是叶子节点
    9. if ((root.left == null) && (root.right == null))
    10. // 记录该条路径
    11. path.add(way);
    12. else {
    13. way += "->"; // 当前节点不是叶子节点,继续递归遍历
    14. dfs(root.left, way, path);
    15. dfs(root.right, way, path);
    16. }
    17. }
    18. return path;
    19. }
    20. public List<String> binaryTreePaths(TreeNode root) {
    21. LinkedList<String> path = new LinkedList();
    22. dfs(root, "", path);
    23. return path;
    24. }
    25. }