原题链接:https://leetcode.com/problems/smallest-string-starting-from-leaf/
1. 题目介绍
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.)
给出一个二叉树,二叉树的每一个节点都有一个范围在0~25的数值,这些数值代表了从a到z的26个小写字母。值为0代表a,值为1代表b,以此类推。
寻找从叶子节点开始,在根节点结束的,字典序最小的字符串。
一个需要注意的地方是,如果两个字符串有相同的前缀,那么前缀较小的那个字符串是字典序更小的字符串。比如ab就比aba的字典序要小。
叶子节点是指没有子节点的节点。
2. 解题思路
自顶向下
如果需要频繁对字符串进行拼接操作,不要使用String类,而应该使用StringBuffer类或者StringBuilder类,在这里我使用的是StringBuffer类。
本方法参考了LeetCode的官方题解:
https://leetcode.com/problems/smallest-string-starting-from-leaf/solution/
自顶向下,记录从根节点到达叶子节点的每一个节点值对应的字母。
当到达叶子节点时,使用reverse函数将StringBuffer类的所有字符反转,并且使用compareTo函数和已经保存的ans字符串进行比较,compareTo函数会比较两个字符串的字典序,如果返回值小于0,说明当前字符串的字典序比ans小,于是更新ans字符串。
实现代码
class Solution {
String ans = "{";
public String smallestFromLeaf(TreeNode root) {
StringBuffer buf = new StringBuffer();
helper(root, buf);
return ans;
}
public void helper(TreeNode node, StringBuffer buf){
if(node == null){
return;
}
buf.append( (char)('a' + node.val) );
if(node.left == null && node.right == null){
buf.reverse();
String s = buf.toString();
buf.reverse();
if(s.compareTo(ans) < 0 ){
ans = s;
}
}
helper(node.left , buf );
helper(node.right, buf );
buf.deleteCharAt( buf.length() - 1);
}
}
3. 参考资料
https://leetcode.com/problems/smallest-string-starting-from-leaf/solution/