当前位置:网站首页>【二叉树】从二叉树一个节点到另一个节点每一步的方向
【二叉树】从二叉树一个节点到另一个节点每一步的方向
2022-08-03 13:01:00 【豪冷啊】
0x00 题目
给你一棵 二叉树 的根节点 root
这棵二叉树总共有 n 个节点
每个节点的值为 1 到 n 中的一个整数
且互不相同
给你一个整数 startValue
表示起点节点 s 的值
和另一个不同的整数 destValue
表示终点节点 t 的值
请找到从节点 s 到节点 t 的 最短路径
并以字符串的形式返回每一步的方向
每一步用 大写 字母 ‘L’ ,‘R’ 和 ‘U’ 分别表示一种方向:
L 表示从一个节点前往它的 左孩子 节点R 表示从一个节点前往它的 右孩子 节点U 表示从一个节点前往它的 父 节点
请你返回从 s 到 t 最短路径 每一步的方向
0x01 思路
因为有 2 个目标
所以有 2 条路径
先把 2 条路径找出来
然后再找出最近的公共祖先
最后再拼接路径
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 getDirections(_ root: TreeNode?, _ startValue: Int, _ destValue: Int) -> String {
guard let root = root else { return "" }
// 第一条路径
var path1: [(TreeNode, String)] = []
// 第二条路径
var path2: [(TreeNode, String)] = []
// 结果
var res = ""
// 节点和方向
var arr: [(TreeNode, String)] = []
func dfs(_ root: TreeNode?, _ val: Int, _ type: String) {
guard let root = root else { return }
// 添加
arr.append((root, type))
if root.val == val {
if val == startValue {
path1 = Array(arr)
}else if val == destValue {
path2 = Array(arr)
}
return
}
dfs(root.left, val, "L")
dfs(root.right, val, "R")
// 往回走了,删除最后一个
arr.removeLast()
}
// 查找第一条路径
dfs(root, startValue, "")
arr.removeAll()
// 查找第二条路径
dfs(root, destValue, "")
var idx1 = 0
var idx2 = 0
let idx = min(path1.count, path2.count)
// 去掉路径中相同的前缀
while idx1 < idx && idx2 < idx {
let t1 = path1[idx1]
let t2 = path2[idx2]
if t1.0.val == t2.0.val {
idx1 += 1
idx2 += 1
}else{
break
}
}
// 第一条路径是从下往上走,所以把方向全部调整为 `U`
for _ in idx1..<path1.count {
res += "U"
}
// 拼接第二条路径
for i in idx2..<path2.count {
res += path2[i].1
}
return res
}
0x03 我的小作品
欢迎体验我的作品之一:小五笔 86 版
五笔学习好帮手~App Store 搜索即可~
边栏推荐
- 如何让history历史记录前带时间戳
- In order to counteract the drop in sales and explore the low-end market, Weilai's new brand products are priced as low as 100,000?
- Jmeter use
- Graphic animation and button animation of an animation basic component
- Golang sync.WaitGroup
- Classes and objects (upper)
- 云计算服务主要安全风险及应对措施初探
- Golang dictionary map
- 便携烙铁开源系统IronOS,支持多款便携DC, QC, PD供电烙铁,支持所有智能烙铁标准功能
- [Deep Learning] Overview of Efficient and Lightweight Semantic Segmentation
猜你喜欢
![[R] Use grafify for statistical plotting, ANOVA, intervention comparisons, and more!](/img/bd/85d0f2f42a449f3b09fe3657d845f2.png)
[R] Use grafify for statistical plotting, ANOVA, intervention comparisons, and more!
![[Blue Bridge Cup Trial Question 48] Scratch Dance Machine Game Children's Programming Scratch Blue Bridge Cup Trial Question Explanation](/img/4c/b41d64c13d6903aa38cc46dea44519.png)
[Blue Bridge Cup Trial Question 48] Scratch Dance Machine Game Children's Programming Scratch Blue Bridge Cup Trial Question Explanation

IronOS, an open source system for portable soldering irons, supports a variety of portable DC, QC, PD powered soldering irons, and supports all standard functions of smart soldering irons

An animation optimization of traditional guide layer animation

An introduction to 3D tools

365天挑战LeetCode1000题——Day 048 有序队列 脑筋急转弯

An工具介绍之宽度工具、变形工具与套索工具

The components of the basis of An animation movie clip animation between traditional filling

技术分享 | 接口自动化测试如何搞定 json 响应断言?

HCIP 第十六天笔记(SVI、生成树协议)
随机推荐
查看GCC版本_qt版本
【R】用grafify搞定统计绘图、方差分析、干预比较等!
Secure Custom Web Application Login
leetcode16 Sum of the closest three numbers (sort + double pointer)
Notepad++ 安装jsonview插件
欧曼自动挡、银河大马力、行星新产品 欧曼全新产品以燎原之势赢领市场
[Microservice] Multi-level cache
HCIP第十五天笔记(企业网的三层架构、VLAN以及VLAN 的配置)
汉源高科G8032标准ERPS环网交换机千兆4光10电工业以太网交换机环网+WEB管理+SNMP划VLAN
使用百度EasyDL实现施工人员安全装备检测
An animation based button animation combined with basic code
An工具介绍之形状工具及渐变变形工具
leetcode 11. The container that holds the most water
An基本工具介绍之选择线条工具(包教会)
[OpenCV] Book view correction + advertising screen switching Perspective transformation image processing
self-discipline
Nodejs 安装依赖cpnm时,install 出现Error: Cannot find module ‘fs/promises‘
Redis 6 的多线程
[Practical skills] APP video tutorial for updating APP in CANFD, I2C, SPI and serial port mode of single-chip bootloader (2022-08-01)
Golang 接口 interface