当前位置:网站首页>【二叉树】从叶结点开始的最小字符串
【二叉树】从叶结点开始的最小字符串
2022-06-28 13:48:00 【豪冷啊】
0x00 题目
给定一颗根结点为 root 的二叉树
树中的每一个结点都有一个 [0, 25] 范围内的值
分别代表字母 a 到 z
返回 按字典序最小 的字符串
该字符串从这棵树的一个叶结点开始
到根结点结束
注:
字符串中任何较短的前缀在 字典序上 都是 较小 的
例如,在字典序上 “ab” 比 “aba” 要小
叶结点是指没有子结点的结点
0x01 思路
因为字符串的构成是
从叶子节点向根节点的方向
所以要使用后序遍历方式
0x02 解法
语言:Swift
树节点:TreeNode
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
解法:
func smallestFromLeaf(_ root: TreeNode?) -> String {
var res = ""
var s = ""
func dfs(_ root: TreeNode?) {
guard let r = root else { return }
// 数字转字符,a - 97
let c = Character(UnicodeScalar(97 + r.val)!)
// 字符转字符串,拼接
s += String(c)
// 到了叶子节点
if r.left == nil && r.right == nil {
var t = String(s)
// 倒序
t = String(t.reversed())
// 比较大小
if res.isEmpty || t < res {
res = t
}
}
dfs(r.left)
dfs(r.right)
// 返回上一层,删除最后一个,也就是回溯算法
s.removeLast()
}
dfs(root)
return res
}
0x03 我的作品
欢迎体验我的作品之一:小五笔小程序
五笔学习好帮手~
微信搜索 XWubi 即可~
边栏推荐
- 正则匹配数字,英文以及英文符号
- How to open an account of Huatai Securities? How to handle the account opening is the safest
- How to open an account on the flush? Is it safe
- SPI interface introduction -piyu dhaker
- Oracle 云基础设施扩展分布式云服务,为组织提供更高的灵活性和可控性
- 如何设计数据可视化平台
- Pytorch main modules
- Explanation of sprintf function in C language
- 其他国产手机未能填补华为的空缺,苹果在高端手机市场已无对手
- yii2编写swoole的websocket服务
猜你喜欢
随机推荐
[codec] write H264 decoder (1) from scratch
Multi dimensional monitoring: the data base of intelligent monitoring
Why do more and more users give up swagger and choose apifox
2.01 backpack problem
众昂矿业着眼氟化工产业,布局新能源产业链
几百行代码实现一个 JSON 解析器
The difference between align items and align content
Play NAS home NAS server setup scheme "suggestions collection"
开源社邀您参加OpenInfra Days China 2022,议题征集进行中~
Prediction of red wine quality by decision tree
嵌入式设计与开发项目-液位检测告警系统
[机缘参悟-32]:鬼谷子-抵巇[xī]篇-面对危险与问题的五种态度
2021计算机三级数据库大题总结
How vscade sets auto save code
Hang Seng Electronics: lightdb, a financial distributed database, has passed a number of evaluations by China Academy of communications technology
Resume template Baidu online disk
Jeecg 官方组件的使用笔记(更新中...)
Is it safe for Huatai Securities to open an account? Is there any risk in opening an account
Operation and maintenance thinking | do you know the relationship between CMDB and monitoring?
正则匹配数字,英文以及英文符号








