257. 二叉树的所有路径

深度优先搜索

class Solution {

    List<String> list = new LinkedList<>();

    public List<String> binaryTreePaths(TreeNode root) {

        if (root == null){
            return list;
        }

        dfs(root, new String());
        return list;
    }

    /**
     * str参数用来记录单条路径
     */
    public void dfs(TreeNode root, String str){

        /**
         * 保证每次递归的root不为空,然后记录值
         */
        str = str + root.val;

        /**
         * 如果该节点是叶子节点,就终止递归,返回记录的该条路径
         */
        if (root.left == null && root.right == null){

            list.add(str);
            return;
        }

        /**
         * 否则继续遍历非空的孩子
         */
        if (root.left != null) {
            dfs(root.left, str + "->");
        }

        if (root.right != null) {
            dfs(root.right, str + "->");
        }
    }
}

/**
 * 时间复杂度 O(n^2)
 * 空间复杂度 O((logn)^2)
 */

https://leetcode-cn.com/problems/binary-tree-paths/

posted @ 2021-12-25 22:13  振袖秋枫问红叶  阅读(35)  评论(0)    收藏  举报