Leetcode 988. Smallest String Starting From Leaf (二叉树遍历好题)

2026国内Claude Code保姆级教程:安装、避坑、防串台全优化 安装 Claude Code CLI + 切换 npm 国内镜像优先配置固定关闭:自动联网、自动项目扫描VSCode 内置终端直接用,不装多余插件会话隔离+指令约束,彻底解决 Rust、小程序 跨语言串台。 阅读详情
  1. Smallest String Starting From Leaf
    Medium
    1.6K
    227
    Companies
    You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters ‘a’ to ‘z’.

Return 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.

Example 1:

Input: root = [0,1,2,3,4,3,4]
Output: “dba”
Example 2:

Input: root = [25,1,3,1,3,0,2]
Output: “adz”
Example 3:

Input: root = [2,2,1,null,1,0,null,0]
Output: “abc”

Constraints:

The number of nodes in the tree is in the range [1, 8500].
0 <= Node.val <= 25

解法1:遍历二叉树即可。
注意这里是要找到顺序最小的字符串,所以gMaxPath要初始化成ascii很大的字符串。而ascii table里面,数字<大写字母<小写字母。在前128个ascii code里面,比’z’还大的只有’{‘,’}‘,‘|’和DEL。所以可以初始化成"{}"。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    string smallestFromLeaf(TreeNode* root) {
        helper(root, "");
        return gMaxPath;
    }
private:
    string gMaxPath = "{}";//'{' or '}' > 'z'
    void helper(TreeNode *root, string path) {
        if (!root) return;
        path += 'a' + root->val;
        if (!root->left && !root->right) {
            reverse(path.begin(), path.end());
            gMaxPath = min(gMaxPath, path);
            return;
        }
        helper(root->left, path);
        helper(root->right, path);
        return;
    }
};

二刷:path改成引用。
需要注意:

  1. 如果不是引用,可以直接调用helper(root, “”),但是如果是引用的话,需要先定义string path = “”, 然后调用helper(root, path)。
  2. 在 if (!root->left && !root->right) {}里面return前也要 path.pop_back();
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    string smallestFromLeaf(TreeNode* root) {
        string path = "";
        helper(root, path);
        return gMaxPath;
    }
private:
    string gMaxPath = "{}";//'{' or '}' > 'z'
    void helper(TreeNode *root, string &path) {
        if (!root) return;
        path += 'a' + root->val;
        if (!root->left && !root->right) {
            string tmp = path;
            reverse(tmp.begin(), tmp.end());
            gMaxPath = min(gMaxPath, tmp);
            path.pop_back();
            return;
        }
        helper(root->left, path);
        helper(root->right, path);
        path.pop_back();
        return;
    }
};
2024年09月CCF-GESP编程能力等级认证Scratch图形化编程二级真题解析 小杨购物 【题目描述】 小杨有n元钱用于购物。商品A的单价是a元,商品B的单价是b元。 小杨想购买相同数量的商品A和商品B。 默认小猫角色和白色背景,编写程序请你帮小杨计算出他最多能够购买多少个商品A和商品B。 【输入描述】 新建变量“n”用于存储小杨购物的金额。 新建变量“a”用于存储商品A的价格。 新建变量“b”用于存储商品B的价格。 1≤n,a,b≤100000 如下图所示: 图片 【输出描述】 新建变量“result”用于存储小杨最多购买商品A和商品B的个数。 如下图所示: 阅读详情

相关推荐

Cheat Engine实战:多级指针逆向破解游戏内存的5个关键步骤(附C++模拟代码)

本文详细解析了使用Cheat Engine进行多级指针逆向破解游戏内存的完整流程。通过5个关键步骤,从定位动态地址到逐层追踪指针链,最终构建稳定指针路径。文章结合C++模拟代码,深入剖析了指针链的底层汇编原理,并提供了高级排查技巧,帮助读者掌握逆向工程中的核心内存追踪技术。

weixin_29239279的博客 313

988. Smallest String Starting From Leaf C++

lexicographically smallest string 是这道题目的关键。 翻译过来,就是字典序最小。也就是你翻字典的时候的顺序最小。 从根到root的所有node拼接的string 就按照递归来做。思路也是divide and conquer。 求字典序最小才是这道题的关键,换言之就是实现strcmp函数。 strcmp一个个的字符按照字典顺序比较A,B 如果A[i] 字符比B[i] 小,那A 的字典序小于B。 如果A[i]字符比B[i]大,那A的字典序大于B。 如果A[i]字符

1038

windows10系统上安装最新版mysql 8.0详细步骤

windows10系统上安装最新版mysql 8.0详细步骤

glei20的博客 6733

[leetcode] 988. Smallest String Starting From Leaf

Description 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 th

Learning from the mistakes 241

发那科机器人Modbus通讯配置全攻略:从IP设置到信号调试

本文详细介绍了发那科机器人Modbus通讯的配置方法,从基础认知到IP设置、端口配置、信号调试及故障排查。重点讲解了UOP和DI/DO信号的配置技巧,帮助工程师快速实现机器人与PLC的稳定通讯,提升自动化系统效率。

weixin_27872611的博客 635

Vivado2022.2下载安装

链接:https://pan.baidu.com/s/1lyfE2d-VmaWC-_aR8ratCQ提取码:mt09。

weixin_61081689的博客 2万+

【LeetCode】988. Smallest String Starting From Leaf 解题报告(C++ & Python)

作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录题目描述题目大意解题方法DFSBFS日期 题目地址:https://leetcode.com/problems/smallest-string-starting-from-leaf/ 题目描述 Given the root of a binary tree, each node h...

负雪明烛 1638

ISO13849功能安全从入门到精通(3):安全功能及其对降低风险的贡献4

例如,如果机器必须在有限速度下运行时进行设置,那么在低加速度值下进行设置时,参数P1将是正确的选择:随着危险缓慢出现并给予足够的运动自由,操作员将能够移出危险区域。例如,在无故障的条件下,在操作者的手的方向移动的滚子不能陷住它。在所有其他情况下,F1是正确的选择,前提是危险暴露的持续时间不超过机器总操作时间的1/20。需求来源于必要的风险降低。由于这些考虑而降低的PLr在任何情况下都不得低于通过比较方式考虑的机器的PLr,因为并不能从事故发生率低和严重程度低得出实施的安全功能提供的安全水平高于要求。

wdconan001的博客 844

Leetcode 988:从叶结点开始的最小字符串(超详细的解法!!!)

给定一颗根结点为 root 的二叉树,书中的每个结点都有一个从 0 到 25 的值,分别代表字母 'a' 到 'z':值 0 代表 'a',值 1 代表 'b',依此类推。 找出按字典序最小的字符串,该字符串从这棵树的一个叶结点开始,到根结点结束。 (小贴士:字符串中任何较短的前缀在字典序上都是较小的:例如,在字典序上 “ab” 比 “aba” 要小。叶结点是指没有子结点的结点。) 示例 1: ...

coordinate的博客 1412

【LangChain编程:从入门到实践】实现多模态代理

【LangChain编程:从入门到实践】实现多模态代理 关键词:LangChain, 多模态代理, 自然语言处理, 机器学习, 知识图谱, 对话系统, 代码生成, AI代理 1. 背景介绍 随着人工智

欢迎来到我的CSDN空间!这里聚焦AI大模型应用实战,分享前沿技术、实战案例与开发经验。 587

Python爬虫实战:利用最新技术爬取B站视频信息

本文详细介绍了如何使用Python最新技术构建一个功能完善的B站视频信息爬虫。我们从基础爬取开始,逐步深入到反反爬策略、异步处理、数据存储和分析等高级主题。更智能的反反爬策略:使用机器学习识别验证码更高效的分布式架构:结合Kubernetes实现弹性伸缩实时数据管道:将爬取的数据实时推送到数据分析平台多平台支持:扩展支持抖音、YouTube等其他视频平台。

2201_76125261的博客 1047

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 lexicographi...

IPOC_BUPT的博客 402

LeRobot 入门教程(四)SO-101机械臂组装教程

《SO-101机器人组装与配置指南》详细介绍了旗舰机器人SO-101的完整搭建流程。从获取3D打印零件、安装LeRobot软件和FeetechSDK,到分步组装6个关节的机械臂结构(含夹爪/手柄选项),指南提供了清晰的螺丝规格和安装位置说明。重点包括:电机ID/波特率设置方法、USB端口识别技巧、领导者/跟随者臂的校准流程,以及故障排查建议。完成组装后,用户可通过配套Python脚本校准机器人,为后续的自主学习任务做好准备。文档附有视频演示和技术支持通道,确保用户顺利完成机器人部署。

2506_90492529的博客 2605

LeetCode 988. Smallest String Starting From Leaf

原题链接在这里:https://leetcode.com/problems/smallest-string-starting-from-leaf/ 题目: Given therootof a binary tree, each node has a value from0to25representing the letters'a'to'z': a value of0re...

weixin_30537391的博客 155

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

LeetCode 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

Tech in Pieces 336

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

LeetCode //C - 988. Smallest String Starting From Leaf

Article Summary Problem Description: Given a binary tree where each node has a value between 0 and 25, representing the letters 'a' to 'z', find the lexicographically smallest string formed by the paths from a leaf node to the root node. Solution: Use De

Made in Code 371

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

【leetcode】988. Smallest String Starting From Leaf

题目如下: Given therootof a binary tree, each node has a value from0to25representing the letters'a'to'z': a value of0represents'a', a value of1represents'b', and so on. Find the lexicogr...

weixin_34249678的博客 92

【Leetcode】988. Smallest String Starting From Leaf

题目地址: https://leetcode.com/problems/smallest-string-starting-from-leaf/ 给定一棵二叉树,求其所有从叶子到树根的路径中字典序最小的那个。题目保证节点只含0∼250\sim 250∼25的整数,并且路径要将数字转为英文小写字母,000对应aaa,111对应bbb以此类推。 思路是DFS。当DFS到叶子的时候,更新答案即可。回溯的时候需要多加小心。代码如下: public class Solution { private S

数学、算法爱好者的博客 174

leetcode二叉树 找路径_[LeetCode] 988. Smallest String Starting From Leaf 从叶结点开始的最小字符串...

Given the rootof a binary tree, each node has a value from 0to 25representing the letters 'a'to 'z': a value of 0represents 'a', a value of 1represents 'b', and so on.Find the lexicographic...

weixin_36252618的博客 113

Leetcode-988 Smallest String Starting From Leaf(从叶结点开始的最小字符串)

1 #define pb push_back 2 #define _for(i,a,b) for(int i = (a);i < (b);i ++) 3 class Solution 4 { 5 public: 6 void preorder(vector<int> v,TreeNode* root,string &s) ...

weixin_30486037的博客 147

leetcode 988. Smallest String Starting From Leaf 从叶结点开始的最小字符串

Problem:首先拿到所有叶子nodes的列表,以及每个nodes的父节点哈希表,,然后从叶子往上遍历,拿到字符串,拿到最小值即可或者用递归的方式拿到所有可能。

邹九的个人博客 91

[LeetCode] 988. Smallest String Starting From Leaf

原题链接:https://leetcode.com/problems/smallest-string-starting-from-leaf/

Ber03的博客 343

LeetCode 3884.双端字符匹配:半次遍历

LeetCode 3884.双端字符匹配:半次遍历 给你一个长度为 n 的字符串 s,其中只包含小写英文字母。 返回最小的下标 i,使得 s[i] == s[n - i - 1]。 如果不存在这样的下标,返回 -1。

<font color="Pink">Tisfy的博客</font> 169

力扣 1201. 丑数 III

LeetCode 原题:1201. 丑数 III 今天的每日一题 只能说还可以,不是很难,虽然我一开始也没想到,我本来以为这个题类似归并排序的 那种,把每个数的前n个小的倍数放到一个优先对列中,不过这样有重复的,之后换成set 还是不行超时了。看到题解才恍然大悟,可以用二分和容斥原理来判断这个数前面有多少数比它小……给定四个整数 、、、。如果一个正整数能够被 、、 中的至少一个整除,那么它就是丑数。请返回第 个丑数。示例: 二、解题思路 这道题的核心是:二分答案 + 容斥原理。可以把它想象成三个社团分别招

yydschdyyds的博客 198

【LeetCode 热题 100】142. 环形链表 II|哈希表、快慢指针(Python)

【LeetCode 热题 100】【142. 环形链表 II】|哈希表、快慢指针(Python)

weixin_70673823的博客 346

LeetCode Hot 100 -- (141.环形链表) 思路与总结

本文详解链表环检测问题,先介绍暴力法:用HashSet记录访问过的节点,时间复杂度O(n),空间O(n)。强调必须存节点而非值,否则会误判(如[1,1,1])。随后提出优化方案——快慢指针:慢指针走1步,快指针走2步,若有环则必相遇;若无环,快指针先达末尾。关键点:循环条件需检查fast和fast.next,且先移动再比较。总结:遇环、中点、倒数第k个等题型,优先考虑快慢指针,同一工具可多场景复用。

NGEFF的博客 183
上一篇: LintCode 1024 · Number of Matching Subsequences (binary search 好题)
下一篇: Leetcode 1022. Sum of Root To Leaf Binary Numbers (树遍历题)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址