当前位置:网站首页>【二叉树】二叉树的完全性检验
【二叉树】二叉树的完全性检验
2022-06-23 03:47:00 【豪冷啊】
0x00 题目
给定一个二叉树的 root
确定它是否是一个 完全二叉树
在一个 完全二叉树 中
除了最后一个节点外
所有节点都是完全被填满的
并且最后一个节点中的所有节点
都是尽可能靠左的
它可以包含 1 到 2h 节点之间的最后一级 h
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 isCompleteTree(_ root: TreeNode?) -> Bool {
var queue: [TreeNode?] = []
// 记录是否遍历到了 空节点
var flag: Bool = false
queue.append(root)
while !queue.isEmpty {
let node = queue.removeFirst()
if node == nil {
// 出现了空节点
flag = true
continue
}else{
// 出现空节点后,又出现了非空节点,所以不是完全二叉树
if flag {
return false
}
queue.append(node?.left)
queue.append(node?.right)
}
}
return true
}
0x03 我的作品
欢迎体验我的作品之一:小笔记-XNote
让笔记一步到位App Store 搜索即可~
边栏推荐
- Sequence table lookup
- 怎么使用Shell脚本实现监测文件变化
- SVG+JS智能家居监控网格布局
- Sessions and Daemons
- It supports running in kubernetes, adds multiple connectors, and seatunnel version 2.1.2 is officially released!
- 靜態查找錶和靜態查找錶
- Idea import module
- linux下的开源数据库是什么
- mysql存储引擎之Myisam和Innodb的区别
- AI video cloud vs narrowband HD, who is the favorite in the video Era
猜你喜欢
随机推荐
Code refactoring Guide
Similar to RZ / SZ, trzsz supporting TMUX has released a new version
PTA:7-61 师生信息管理
Deploying Apache pulsar on kubesphere
mysql能不能在linux中使用
虫子 日期类 下 太子语言
浅析2022年物联网现状
PTA: Simulation Implementation of 7-86 set (function template)
Sessions and Daemons
How MySQL deletes a row of data in a table
靜態查找錶和靜態查找錶
Idea import module
PTA:7-67 友元很简单2016final
顺序表查找
自媒体时代的贤内助——AI 视频云
Compilation, installation and global configuration section description of haproxy
在线文本过滤小于指定长度工具
svg d3.js生成tree树状图
[tcapulusdb knowledge base] [list table] example code for replacing the data at the specified location in the list
How the innovative use of adobe international certification 𞓜 3D changes the entire industry
![[advanced binary tree] AVLTree - balanced binary search tree](/img/a5/aef68dd489ef5545e5b11ee2d3facc.png)








