当前位置:网站首页>【二叉树】根据描述创建二叉树
【二叉树】根据描述创建二叉树
2022-08-04 15:38:00 【豪冷啊】
0x00 题目
给你一个二维整数数组 descriptions
其中 descriptions[i] = [parenti, childi, isLefti] 表示parenti 是 childi 在 二叉树 中的 父节点
二叉树中各节点的值 互不相同
此外:
如果 isLefti == 1 ,那么 childi 就是 parenti 的左子节点
如果 isLefti == 0 ,那么 childi 就是 parenti 的右子节点
请你根据 descriptions 的描述来构造二叉树并返回其 根节点
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 createBinaryTree(_ descriptions: [[Int]]) -> TreeNode? {
if descriptions.isEmpty { return nil }
// 值对应的节点
var dic: [Int:TreeNode] = [:]
// 值对应的父节点
var per: [Int:TreeNode] = [:]
// 那些父节点的值
var arr: [Int] = []
for i in 0..<descriptions.count {
let t = descriptions[i]
let p = t[0]
let c = t[1]
let isLeft = t[2]
// 取出父节点和子节点
var pNode = dic[p]
var cNode = dic[c]
// 不存在就创建
if pNode == nil {
pNode = TreeNode(p)
dic[p] = pNode
// 添加到数组
arr.append(p)
}
if cNode == nil {
cNode = TreeNode(c)
dic[c] = cNode
}
// 值对应的父节点
per[c] = pNode
if isLeft == 1 {
pNode!.left = cNode
}else{
pNode!.right = cNode
}
}
var root: TreeNode? = nil
// 从可能的父节点中寻找,没有父节点的,就是根节点
for i in 0..<arr.count {
let val = arr[i]
if per[val] == nil {
root = dic[val]
}
}
return root
}
0x03 我的小作品
欢迎体验我的作品之一:小五笔
五笔学习好帮手~App Store 搜索即可~
边栏推荐
猜你喜欢

AAAI‘22 推荐系统论文梳理

A detailed explanation of what is software deployment

FTP协议抓包-工具wireshark与filezilla

SAP ABAP SteamPunk 蒸汽朋克的最新进展 - 嵌入式蒸汽朋克

For循环控制

洛谷题解P1028 数的计算

从-99打造Sentinel高可用集群限流中间件

GPS satellite synchronization clock, NTP network synchronization clock, Beidou clock server (Jingzhun)

24、shell编程-流程控制

DevOps平台中的制品库是什么?有什么用处?
随机推荐
Roslyn 在多开发框架让 msbuild 的 Target 仅运行一次
Unity AR阴影投射透明地面 仅渲染模型实时阴影 Shader实现
DocuWare平台——用于文档管理的内容服务和工作流自动化的平台(上)
Taurus.MVC WebAPI 入门开发教程2:添加控制器输出Hello World。
《电磁兼容防护EMC》学习笔记
tif转mat
What is the difference between member variable and local variable
RSA306B,500,600系列API接口代码
FTP协议抓包-工具wireshark与filezilla
吴恩达机器学习[12]-机器学习系统设计
IP报文头解析
多线程编程之优先级翻转问题
全球电子产品需求放缓,三星手机越南工厂每周只需要干 3~4 天
DocuWare Platform - Content Services and Workflow Automation Platform for Document Management (Part 1)
基于 Next.js实现在线Excel
你以为在做的是微服务?不!你做的只是分布式单体!
Legal education combined with VR panorama, intuitively feel and learn the spirit of the rule of law
dot net core 使用 usb
明明加了唯一索引,为什么还是产生重复数据?
7 天学个Go,Go 结构体 + Go range 来学学