关于我 / About Me#

你好!我是 tioryio

🛠️ 关于本站#

本站使用 Astro 框架构建,采用了 Firefly模板

Firefly 是一款基于 Astro 框架开发的清新美观且现代化个人博客主题,专为技术爱好者和内容创作者设计。该主题融合了现代 Web 技术栈,提供了丰富的功能模块和高度可定制的界面,让您能够轻松打造出专业且美观的个人博客网站。

CuteLeaf
/
Firefly
Waiting for api.github.com...
00K
0K
0K
Waiting...

📫 联系方式#

如果你想和我交流技术问题,分享有趣的想法,或者只是想打个招呼,欢迎通过以下方式联系我:

关于河马#

package main
import (
"fmt"
)
// 河马与二叉树节点
type Hippo struct {
Name string
Weight int // kg
}
type Node struct {
H Hippo
Left, Right *Node
}
// 按体重插入(体重相同放右侧)
func Insert(root *Node, h Hippo) *Node {
if root == nil {
return &Node{H: h}
}
if h.Weight < root.H.Weight {
root.Left = Insert(root.Left, h)
} else {
root.Right = Insert(root.Right, h)
}
return root
}
// 中序遍历(体重从小到大)
func InOrder(n *Node, visit func(Hippo)) {
if n == nil {
return
}
InOrder(n.Left, visit)
visit(n.H)
InOrder(n.Right, visit)
}
// 层序遍历(按层打印)
func LevelOrder(n *Node, visit func(level int, h Hippo)) {
if n == nil {
return
}
type pair struct {
node *Node
level int
}
q := []pair{{n, 0}}
for len(q) > 0 {
p := q[0]
q = q[1:]
visit(p.level, p.node.H)
if p.node.Left != nil {
q = append(q, pair{p.node.Left, p.level + 1})
}
if p.node.Right != nil {
q = append(q, pair{p.node.Right, p.level + 1})
}
}
}
// 统计超过阈值的河马数量
func CountHeavier(n *Node, minWeight int) int {
if n == nil {
return 0
}
count := 0
if n.H.Weight > minWeight {
count = 1
}
return count + CountHeavier(n.Left, minWeight) + CountHeavier(n.Right, minWeight)
}
// 寻找最重河马
func Heaviest(n *Node) (Hippo, bool) {
if n == nil {
return Hippo{}, false
}
// 在 BST 中,最右节点即最重
cur := n
for cur.Right != nil {
cur = cur.Right
}
return cur.H, true
}
func main() {
// 构建“二叉树上的河马”
var root *Node
herd := []Hippo{
{"Tio", 1500},
{"Mio", 1300},
{"Kira", 1800},
{"Nia", 1200},
{"Zoe", 1700},
{"Luna", 1600},
}
for _, h := range herd {
root = Insert(root, h)
}
fmt.Println("中序遍历(按体重升序):")
InOrder(root, func(h Hippo) { fmt.Printf("%s(%dkg) ", h.Name, h.Weight) })
fmt.Println()
fmt.Println("\n层序遍历(按层):")
LevelOrder(root, func(level int, h Hippo) {
fmt.Printf("L%d: %s(%dkg)\n", level, h.Name, h.Weight)
})
fmt.Printf("\n> 统计体重大于 1550kg 的河马数量:%d\n", CountHeavier(root, 1550))
if max, ok := Heaviest(root); ok {
fmt.Printf("> 最重的河马:%s(%dkg)\n", max.Name, max.Weight)
}
}

感谢你的来访!希望在这里能找到对你有用的内容。Firefly博客系统完全开源,如果喜欢的话,不妨给个GitHub点个Star ⭐ 支持一下!

目录