[LeetCode] 988. Smallest String Starting From Leaf

45 篇文章 0 订阅

原题链接: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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值