当前位置:网站首页>【二叉树】最大二叉树 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 搜索即可~
边栏推荐
- The first technology podcast month will be launched soon
- Newton method (optimization of two variable functions)
- Cookie encryption 12
- 模块导入reload方法
- Varnish foundation overview 4
- Sentinel source code analysis Part 7 - sentinel adapter module - Summary
- 【论文写作】英文论文写作指南
- 首届·技术播客月开播在即
- In depth analysis of a large number of clos on the server_ The root of wait
- 【推荐系统】基于用户的协同过滤简明原理与代码实现
猜你喜欢

Ctfshow competition original title 680-695

一文读懂,MES管理系统模块功能

【论文写作】英文论文写作指南

The Web3 era is coming? Inventory of five Web3 representative projects | footprint analytics

Cookie encryption 8

How to seamlessly transition from traditional microservice framework to service grid ASM

js返回内容被unicode编码

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

3-6sql injection website instance step 5: break through the background to obtain web administrator permissions

画画水族馆的应用特色及功能
随机推荐
Varnish 基础概览3
【图神经网络】图分类学习研究综述[3]:图分类方法评价及未来研究方向
Cookie encryption 9
Cantilever beam calculation [matlab code]
Pytorch 修改hook源码 获取Per-Layer输出参数(带layer name)
cookie加密8
传统微服务框架如何无缝过渡到服务网格 ASM
ctfshow 大赛原题 680-695
What should be paid attention to in the design and production of the Urban Planning Museum
C language final without failing (Part 1)
Varnish foundation overview 1
Application of pointer in STC89C52 single chip microcomputer and demonstration of practical cases
Cub school learning: manual query and ADC in-depth use
Varnish foundation overview 5
Varnish 基础概览1
Sentinel source code analysis Part 6 - sentinel adapter module Chapter 4 zuul2 gateway
OpenCV和Image之间的转换(亲测有效)
Mysql 监控1
Cookie encryption 10
Database application