当前位置:网站首页>【二叉树】将二叉搜索树变平衡
【二叉树】将二叉搜索树变平衡
2022-07-26 18:49:00 【豪冷啊】
0x00 题目
给你一棵二叉搜索树,请你返回一棵 平衡后 的二叉搜索树
新生成的树应该与原来的树有着相同的节点值
如果有多种构造方法,请你返回任意一种
如果一棵二叉搜索树中
每个节点的两棵子树高度差不超过 1
我们就称这棵二叉搜索树是 平衡的
0x01 思路
通过对二叉搜索树进行中序遍历
得到一个升序数组
再通过升序数组构建平衡二叉树
取数组中间的数,生成根节点
则数组左右两边的的数量差值不会超过 1递归地对左右两部分进行构建即可
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 balanceBST(_ root: TreeNode?) -> TreeNode? {
var arr: [Int] = []
// 中序遍历
func dfs(_ root: TreeNode?) {
guard let r = root else { return }
dfs(r.left)
arr.append(r.val)
dfs(r.right)
}
// 构建平衡二叉树
func build(_ nums: [Int], _ left: Int, _ right: Int) -> TreeNode? {
if left > right { return nil }
// 取中值
let mid = (left + right) / 2
let val = nums[mid]
let node = TreeNode(val)
// 递归构建
node.left = build(nums, left, mid-1)
node.right = build(nums, mid+1, right)
return node
}
dfs(root)
let node = build(arr, 0, arr.count-1)
return node
}
0x03 我的小作品
欢迎体验我的作品之一:小笔记-XNote
做笔记,一步到位!
传笔记,一键到位!App Store 搜索即可~
边栏推荐
- The authentication type 10 is not supported
- Familiarize you with the "phone book" of cloud network: DNS
- 2022牛客多校联赛第三场 题解
- Redis introduction
- Redis介绍
- Pads draw 2.54mm row needle
- Several ways to view containers
- [MySQL must know and know] log details
- Leetcode-138-copy linked list with random pointer
- 基于华为云 IOT 设计智能称重系统 (STM32)【二】结尾有资料
猜你喜欢

Detailed explanation of Yolo V2

Leetcode daily practice - 26. Delete duplicates in an ordered array

How to compress the traffic consumption of APP under mobile network in IM development

YOLO V2详解

线性代数第3章向量

Leetcode daily practice - 27. Remove elements

Solidity中call函数详解

服务器内存故障预测居然可以这样做

Chapter 9 practical modeling technology

拿铁DHT-PHEV产品响当当,销量会不会让李瑞峰想通了呢?
随机推荐
Leetcode daily practice - 189. Rotation array
Selenium + case of Web Automation Framework
Leetcode-138-copy linked list with random pointer
数据库设计三大范式
Live video source code to achieve the advertising effect of scrolling up and down
【PHP】将 SESSION 数据保存到 Redis
PyQt5快速开发与实战 3.6 打包资源文件
IM即时通讯开发如何压缩移动网络下APP的流量消耗
Implementing DDD based on ABP -- domain logic and application logic
PHP 替换中文字符的方法
Will 3R balanced financial products have risks? Is it risky?
How to adjust the abnormal win11 USB drive to normal?
J1: why is redis so fast + basic structure
[PHP] MySQL native PHP operation - Tianlong eight steps
Linux regularly backs up the database and deletes the data n days ago
Linux 定时备份数据库并删除 N 天以前的数据
Leetcode daily practice - 27. Remove elements
iPhone开发 数据持久化总结(终结篇)—5种数据持久化方法对比
Cuda11.2 corresponding pytorch installation
Reentrantlock learning - Basic Attributes