数据结构【Golang实现】--------BinaryTree

目录

1.结构定义

2.InsertItem()

3.SearchItem()

4.PreorderTraversal()

5.InorderTraversal()

6.PostorderTraversal()


1.结构定义

type Node struct {
	data   int
	parent *Node
	left   *Node
	right  *Node
}

type BinaryTree struct {
	root *Node
}

2.InsertItem()

func (tree *BinaryTree) InsertItem(i int) {
	if tree.root == nil {
		tree.root = &Node{data: i}
		return
	}
	currentnode := tree.root
	for {
		if i > currentnode.data {
			if currentnode.right == nil {
				currentnode.right = &Node{data: i, parent: currentnode}
				return
			}
			currentnode = currentnode.right
		} else {
			if currentnode.left == nil {
				currentnode.left = &Node{data: i, parent: currentnode}
				return
			}
			currentnode = currentnode.left
		}

	}
}

3.SearchItem()

func (tree *BinaryTree) SearchItem(i int) (*Node, bool) {
	if tree.root == nil {
		return nil, false
	}
	current := tree.root
	for current != nil {
		if i == current.data {
			return current, true
		} else if i > current.data {
			current = current.right
		} else if i < current.data {
			current = current.left
		}

	}
	return nil, false
}

4.PreorderTraversal()

func (tree *BinaryTree) PreorderTraversal(subtree *Node, callback func(i int)) {
	callback(subtree.data)
	if subtree.left != nil {
		tree.PreorderTraversal(subtree.left, callback)
	}
	if subtree.right != nil {
		tree.PreorderTraversal(subtree.right, callback)
	}
}

5.InorderTraversal()

func (tree *BinaryTree) InorderTraversal(subtree *Node, callback func(i int)) {
	if subtree.left != nil {
		tree.PreorderTraversal(subtree.left, callback)
	}
	callback(subtree.data)
	if subtree.right != nil {
		tree.PreorderTraversal(subtree.right, callback)
	}
}

6.PostorderTraversal()

func (tree *BinaryTree) PostorderTraversal(subtree *Node, callback func(i int)) {
	if subtree.left != nil {
		tree.PreorderTraversal(subtree.left, callback)
	}
	if subtree.right != nil {
		tree.PreorderTraversal(subtree.right, callback)
	}
	callback(subtree.data)
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值