Golang 实现简单线段树

本文介绍了如何使用Golang实现一个简单的线段树数据结构,通过实例代码详细阐述其功能和操作过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用Go撸了个简单线段树练练手

package main

import "fmt"

//线段树节点
type Node struct {
	L     int
	R     int
	Left  *Node
	Right *Node
	Cover int
}

//建树
func (this *Node) build(l, r int) *Node {
	this.L = l
	this.R = r
	this.Cover = 0
	mid := (this.L + this.R) >> 1

	if (l + 1) < r {
		if this.L != mid {
			NewLeftNode := Node{}
			this.Left = NewLeftNode.build(this.L, mid)
		}
		if this.R != mid {
			NewRightNode := Node{}
			this.Right = NewRightNode.build(mid, this.R)
		}
		return this
	} else {
		return this
	}
}

//插入
func (this *Node) Insert(l, r int) {
	mid := (this.L + this.R) >> 1
	if l == this.L && r == this.R {
		//若插入的线段正好被包含,结束递归
		this.Cover = 1
	} else if r <= mid {
		if this.Left != nil {
			this.Left.Insert(l, r)
		}
	} else if l >= mid {
		if this.Right != nil {
			this.Right.Insert(l, r)
		}
	} else {
		if this.Left != nil {
			this.Left.Insert(l, mid)
		}
		if this.Right != nil {
			this.Right.Insert(mid, r)
		}
	}
}

//统计
func (this *Node) Sum() int {
	if this.Cover == 1 {
		return this.R - this.L
	} else if this.R-this.L == 1 {
		return 0
	}
	return this.Left.Sum() + this.Right.Sum()
}

//中序遍历
func (this *Node) InorderTraversal() {
	if this != nil {
		this.Left.InorderTraversal()
		fmt.Println(this)
		this.Right.InorderTraversal()
	}
}

func main() {
	Tree := Node{}
	Tree.build(1, 6)
	Tree.Insert(1, 2)
	Tree.Insert(3, 5)
	Tree.Insert(4, 6)
	Tree.Insert(5, 6)
	Tree.InorderTraversal()
	fmt.Println(Tree.Sum())
}

输出:

&{1 2 <nil> <nil> 1}
&{1 3 0xc00006e2a0 0xc00006e2d0 0}
&{2 3 <nil> <nil> 0}
&{1 6 0xc00006e270 0xc00006e300 0}
&{3 4 <nil> <nil> 1}
&{3 6 0xc00006e330 0xc00006e360 0}
&{4 5 <nil> <nil> 1}
&{4 6 0xc00006e390 0xc00006e3c0 1}
&{5 6 <nil> <nil> 1}
4

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值