【Golang】用 go 实现二叉搜索树

这篇博客记录了作者在周末用Go语言实现二叉搜索树的过程,作为学习Go的实践项目。实现了包括节点插入和删除等基本操作。
摘要由CSDN通过智能技术生成

今日周六,闲来无事,正好最近学习了go语言,就用go实现了一个简单的二叉搜索树,用于练习,支持插入和删除操作。

package main

import (
	"fmt"
)

type TreeNode struct {
	Value int
	Left  *TreeNode
	Right *TreeNode
}

func CreateNode(value int) *TreeNode {
	return &TreeNode{value, nil, nil}

}

func (node *TreeNode) InOrder() {
	if node != nil {
		node.Left.InOrder()
		fmt.Println(node.Value)
		node.Right.InOrder()
	}
}

func (node *TreeNode) Insert(value int) bool {
	if node == nil {
		node = CreateNode(value)
		return true
	}
	var parent *TreeNode = nil
	var cur *TreeNode = node
	for cur != nil {
		if cur.Value > value {
			parent = cur
			cur = cur.Left
		} else if cur.Value < value {
			parent = cur
			cur = cur.Right
		} else {
			return false
		}
	}
	cur = CreateNode(value)
	if cur.Value < parent.Value {
		parent.Left = cur
	} else {
		parent.Right = cur
	}
	return true
}

func (node *TreeNode) Erase(value int) bool {
	if node == nil {
		return false
	}
	if node.Value == value {
		node = nil
		return true
	}
	var parent *TreeNode
	var cur *TreeNode = node
	for cur != nil {
		if cur.Value > value {
			parent = cur
			cur = cur.Left
		} else if cur.Value < value {
			parent = cur
			cur = cur.Right
		} else {
			if cur.Left == nil {
				if cur == parent.Left {
					parent.Left = cur.Right
				} else {
					parent.Right = cur.Right
				}
			} else if cur.Right == nil {
				if cur == parent.Left {
					parent.Left = cur.Left
				} else {
					parent.Right = cur.Right
				}
			} else {
				var RightMinLeft *TreeNode = cur.Right
				for RightMinLeft.Left != nil {
					parent = RightMinLeft
					RightMinLeft = RightMinLeft.Left
				}
				cur.Value = RightMinLeft.Value
				if RightMinLeft == parent.Left {
					parent.Left = RightMinLeft.Right
				} else {
					parent.Right = RightMinLeft.Right
				}
				RightMinLeft = nil
			}
			return true
		}
	}
	return false
}
func main() {
	var root TreeNode
	root.Insert(4)
	root.Erase(4)
	fmt.Println("******************")
	//root.Value = 4
	root.Insert(2)
	root.Insert(6)
	//root.Insert(4)
	root.Insert(3)
	root.Insert(5)
	root.Insert(1)
	root.Insert(7)
	ret := root.Erase(3)
	fmt.Println(ret)
	root.InOrder()
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值