当前位置:网站首页>【二叉树】最大二叉树 II
【二叉树】最大二叉树 II
2022-06-30 01:28:00 【豪冷啊】
0x00 题目
最大树定义:
一棵树,其中每个节点的值
都大于其子树中的任何其他值
给你最大树的根节点 root 和一个整数 val
把 val 插入这棵树
并返回新的最大二叉树的根节点
0x01 思路
根据构建最大二叉树的规则根节点是给定数组中的最大值
最大值左边是左子树
最大值右边是右子树
新插入的 val 是添加在给定数组最后的
所以 val 应该插入到右子树
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 insertIntoMaxTree(_ root: TreeNode?, _ val: Int) -> TreeNode? {
// 节点为空,则返回一个新节点
guard let r = root else { return TreeNode(val) }
// 节点值比插入值小,则找到位置
if r.val < val {
let node = TreeNode(val)
node.left = r
return node
}
// 插入到右子树
r.right = insertIntoMaxTree(r.right, val)
return r
}
0x03 我的作品
欢迎体验我的作品之一:小编辑器
小巧的在线编辑器
包含多种语言App Store 搜索即可~
边栏推荐
- C语言 一元多项式求导
- Machine learning notes: time series decomposition STL
- Stringredistemplate disconnects and the value disappears
- Analysis of natural frequency and buckling load of cylinder by finite element method
- Cookie encryption 15 login encryption
- What should be paid attention to in the design and production of the Urban Planning Museum
- 如何统一项目中包管理器的使用?
- 手势数字启蒙学习机
- 挖财的课程靠谱吗,让开户安全吗?
- Some thoughts on small program subcontracting and verification of uiniapp subcontracting optimization logic
猜你喜欢

Cookie encryption 12

Some thoughts on small program subcontracting and verification of uiniapp subcontracting optimization logic

如何统一项目中包管理器的使用?

C语言 数组元素循环右移问题

JS reverse request parameter encryption:

Cookie encryption 15 login encryption

The 8th "Internet +" competition - cloud native track invites you to challenge

numpy的索引和图片的索引一样吗?

Kubernetes 核心对象概览详解

C语言 素数对猜想
随机推荐
Kwai reached out to the "supply side" to find the "source" of live broadcast e-commerce?
What should be paid attention to in the design and production of the Urban Planning Museum
【机器学习Q&A】数据抽样和模型验证方法、超参数调优以及过拟合和欠拟合问题
Stimulus reports reporting tool, stimulus creates and builds reports
Varnish 基础概览10
Varnish foundation overview 4
Mysql 监控2
Application of pointer in STC89C52 single chip microcomputer and demonstration of practical cases
[Thesis Writing] English thesis writing guide
cookie加密9
【论文写作】英文论文写作指南
cookie加密11
C语言 我要通过
C language final without failing (Part 1)
Varnish foundation overview 10
JS prototype and prototype chain (Lantern Festival meal)
Resizekit2.net size and resolution independent
JS recursive summation 1-100
How to deal with occasional bugs?
Cookie encryption 15 login encryption