当前位置:网站首页>【二叉树】最大二叉树 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 搜索即可~
边栏推荐
猜你喜欢

Kubernetes 核心对象概览详解
![[Thesis Writing] English thesis writing guide](/img/59/88d34814a88a2da19ed6a236825649.png)
[Thesis Writing] English thesis writing guide

Application features and functions of painting Aquarium

首届技术播客月开播在即

Ansible ad-hoc temporary command

Machine learning notes: time series decomposition STL

Three text to speech artifacts, each of which is very practical

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

Kwai reached out to the "supply side" to find the "source" of live broadcast e-commerce?

JS content confusion, return content encryption
随机推荐
Embedded exit (review and release)
What should be paid attention to in the design and production of the Urban Planning Museum
Cookie encryption 15 login encryption
C语言 成绩排名
Mysql 监控6
【图神经网络】图分类学习研究综述[3]:图分类方法评价及未来研究方向
Questions about database: database attachment
The first technology podcast month will be launched soon
MySQL monitoring 1
Cookie encryption 10
Varnish foundation overview 5
Ansible ad-hoc 临时命令
js返回内容被unicode编码
Varnish foundation overview 10
首届技术播客月开播在即
R语言线性回归模型拟合诊断异常值分析家庭燃气消耗量和卡路里实例带自测题
第八届“互联网+”大赛 | 云原生赛道邀你来挑战
Cookie encryption 12
Varnish foundation overview 7
[machine learning Q & A] data sampling and model verification methods, hyperparametric optimization, over fitting and under fitting problems