988. 从叶节点开始的最小字符串

深度优先搜索

class Solution {

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

    public String smallestFromLeaf(TreeNode root) {

        dfs(root, new String());

        /**
         * 按照字符串的字典序排序
         */
        list.sort(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2) < 0 ? -1 : 1;
            }
        });
        
        return list.get(0);
    }

    /**
     * 深度搜索方法(无返回值)
     * 用一个String按从下到上存储每一条路径的节点字母,到叶子节点后就将其添加进总的列表
     */
    public void dfs(TreeNode root, String str) {

        if (root == null){
            return;
        }

        str = (char)(root.val + 'a') + str;

        if (root.left == null && root.right == null){

            list.add(str);
            return;
        }

        dfs(root.left, str);
        dfs(root.right, str);
    }
}

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

https://leetcode-cn.com/problems/smallest-string-starting-from-leaf/

posted @ 2021-12-28 15:20  振袖秋枫问红叶  阅读(30)  评论(0)    收藏  举报