题目描述
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);//回溯
}
}

本文介绍了一种寻找二叉树中从叶子节点到根节点的最小字典序字符串的方法。通过深度优先搜索策略,递归地构建路径并比较字符串大小,最终确定最小子串。

被折叠的 条评论
为什么被折叠?



