当前位置:网站首页>【二叉树】二叉树的完全性检验
【二叉树】二叉树的完全性检验
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 搜索即可~
边栏推荐
- PTA:7-31 期刊收费
- AI video cloud: a good wife in the era of we media
- Similar to RZ / SZ, trzsz supporting TMUX has released a new version
- SVG+JS智能家居监控网格布局
- flutter系列之:flutter中的Wrap
- Can MySQL be used in Linux
- bubble sort
- Section 2: spingboot unit test
- 如何保证应用程序的安全性
- How the innovative use of adobe international certification 𞓜 3D changes the entire industry
猜你喜欢

Introduction to deep learning

仿360桌面悬浮球插件

如何保证应用程序的安全性

Pytoch --- use pytoch's pre training model to realize four weather classification problems

Halcon glue line detection - template matching, pose transformation, glue width, glue continuity detection

Pytorch---使用Pytorch的预训练模型实现四种天气分类问题

深度学习 TensorFlow入门

城链科技董事长肖金伟:践行数据经济系国家战略,引领数字时代新消费发展!

Online text filter less than specified length tool

高效的远程办公经验 | 社区征文
随机推荐
京东云分布式数据库StarDB荣获中国信通院 “稳定性实践先锋”
Questions about SQL statements
bubble sort
mysql优化,sql执行非常卡顿,不改变sql结构达到10秒内结束
Create a desktop shortcut to your appimage
虫子 日期类 上 太子语言
Idea import module
Xiaojinwei, chairman of Chenglian Technology: implement the national strategy of data economy and lead the development of new consumption in the digital era!
How to solve the problem that the web page fails to log in after the easycvr service is started?
How e-commerce makes use of small programs
PTA:6-71 时钟模拟
leetcode 91. Decode ways (medium)
PTA:7-86 集合的模拟实现(函数模板)
What is the difference between redistemplate and CacheManager operation redis
Flutter怎么实现不同缩放动画效果
P1347 排序(topo)
基于HAProxy实现网页动静分离
Pytorch---使用Pytorch的预训练模型实现四种天气分类问题
Two ways to improve the writing efficiency of hard disk storage data
[Shangshui Shuo series] day three - preview4