988. Smallest String Starting From Leaf

题目描述

Given the root of a binary tree, each node has a value from 0 to 25 representing the letters ‘a’ to ‘z’: a value of 0 represents ‘a’, a value of 1 represents ‘b’, and so on.

Find the lexicographically smallest string that starts at a leaf of this tree and ends at the root.

(As a reminder, any shorter prefix of a string is lexicographically smaller: for example, “ab” is lexicographically smaller than “aba”. A leaf of a node is a node that has no children.)

在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

题目链接

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

方法思路

class Solution {
    //Runtime: 4 ms, faster than 55.51%
    //Memory Usage: 38.7 MB, less than 5.17% 
    String ans = "~";
    public String smallestFromLeaf(TreeNode root) {
        dfs(root, new StringBuilder());
        return ans;
    }

    public void dfs(TreeNode node, StringBuilder sb) {
        if (node == null) return;
        sb.append((char)('a' + node.val));

        if (node.left == null && node.right == null) {
            sb.reverse();
            String S = sb.toString();
            sb.reverse();

            if (S.compareTo(ans) < 0)
                ans = S;
        }

        dfs(node.left, sb);
        dfs(node.right, sb);
        sb.deleteCharAt(sb.length() - 1);//回溯
    }
}

猜你喜欢

转载自blog.csdn.net/IPOC_BUPT/article/details/88775779