当前位置:网站首页>21 - 二叉树的垂直遍历
21 - 二叉树的垂直遍历
2022-07-23 09:19:00 【JH_Cao】
1. 题目
题目描述

思路
/**
思路:
- 从上往下 BFS
- 从左往右 DFS
*/
/**
代码讲解:
0. 定义一个字典,存放每一列的结果 [key: Value] = [Int: [Int]]
- 定义一个队列,存放node
- 定义一个队列,存放位置, 左边-1, 右边+1
- 每次取出队列,更新字典的key - Value
- 遍历字典的value,从左往右遍历,放入res
*/

- 代码
func verticalOrder(_ root: TreeNode?) -> [[Int]] {
var res = [[Int]]()
if root == nil { return res }
var dict: [Int: [Int]] = [Int: [Int]]()
var queueValue = [TreeNode]()
if let root = root {
queueValue.append(root)
}
var queuePosition = [Int]()
queuePosition.append(0)
var leftPos = Int.max
while !queueValue.isEmpty {
let node = queueValue.removeFirst()
let pos = queuePosition.removeFirst()
var subArr = dict[pos, default: [Int]()]
subArr.append(node.val)
dict[pos] = subArr
if node.left != nil {
queueValue.append(node.left!)
queuePosition.append(pos - 1)
}
if node.right != nil {
queueValue.append(node.right!)
queuePosition.append(pos + 1)
}
leftPos = min(leftPos, pos)
}
for i in leftPos..<leftPos + dict.count {
if let subArr = dict[i] {
res.append(subArr)
}
}
return res
}
- 提交结果

边栏推荐
猜你喜欢

Wacom firmware update error 123, digital board driver cannot be updated
![[C language] number guessing game + shutdown applet](/img/2f/643ec964dba7643f91b1bd679a9284.png)
[C language] number guessing game + shutdown applet

基本51单片机点阵汉字显示程序设计

Surrounded Regions

Yunna | how to manage the fixed assets of the company? How to manage the company's fixed assets better?

【FLink】FLink Hash collision on user-specified ID “opt“. Most likely cause is a non-unique ID

手工测试如何转向自动化测试?字节5年自动化经验浅谈一下...

Uni app knowledge points and records of problems and solutions encountered in the project
![Looking for peak [Abstract dichotomy exercise]](/img/99/122e79784f0f07120680d2cbcf89da.png)
Looking for peak [Abstract dichotomy exercise]

C语言实现课堂随机点名系统
随机推荐
转自玉溪信息公开:mRNA新冠疫苗、九洲马破伤风免疫球蛋白等产品有望年内上市。
JS texture style pie chart plug-in
Aruba learning notes 05 configuration architecture WLAN configuration architecture
Summary of JS data type judgment methods
Authing supports Zadig! Unified authentication and rapid docking of cloud native users
Chapter 2 basic query and sorting
CPU,内存,磁盘速度比较
First acquaintance and search set
优化华为云服务器采用Key登陆
AI acceleration gesture recognition experience based on efr32mg24
(heavy chain dissection) Magic Tree
第2章 基礎查詢與排序
Authing 支持 Zadig 啦!云原生用户统一认证快速对接
Program design of dot matrix Chinese character display of basic 51 single chip microcomputer
【论文笔记】基于分层深度强化学习的移动机器人导航方法
【软件测试】盘一盘工作中遇到的 Redis 异常测试
【测试平台开发】十七、接口编辑页面实现下拉级联选择,绑定接口所属模块...
【WinForm】关于截图识别数字并计算的桌面程序实现方案
Consensys Quorum Benchmark Test
在使用 VScode 进行代码格式化后,保存发现代码又变乱了,怎么办?vs去掉格式化