2022-11-26 13:25:13 +08:00
|
|
|
// File: binary_search_tree_test.go
|
|
|
|
// Created Time: 2022-11-26
|
|
|
|
// Author: Reanon (793584285@qq.com)
|
|
|
|
|
|
|
|
package chapter_tree
|
|
|
|
|
2022-12-03 20:25:24 +08:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"testing"
|
|
|
|
)
|
2022-11-26 13:25:13 +08:00
|
|
|
|
|
|
|
func TestBinarySearchTree(t *testing.T) {
|
2022-11-26 16:32:34 +08:00
|
|
|
nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
|
2022-11-26 13:25:13 +08:00
|
|
|
bst := NewBinarySearchTree(nums)
|
2022-12-03 20:25:24 +08:00
|
|
|
fmt.Println("初始化的二叉树为:")
|
2022-11-26 13:25:13 +08:00
|
|
|
bst.Print()
|
|
|
|
|
|
|
|
// 获取根结点
|
|
|
|
node := bst.GetRoot()
|
2022-12-03 20:25:24 +08:00
|
|
|
fmt.Println("二叉树的根结点为:", node.Val)
|
2022-11-26 13:25:13 +08:00
|
|
|
// 获取最小的结点
|
|
|
|
node = bst.GetMin(bst.GetRoot())
|
2022-12-03 20:25:24 +08:00
|
|
|
fmt.Println("二叉树的最小结点为:", node.Val)
|
2022-11-26 13:25:13 +08:00
|
|
|
|
|
|
|
// 查找结点
|
2022-12-29 14:44:15 +08:00
|
|
|
node = bst.Search(7)
|
2022-12-03 20:25:24 +08:00
|
|
|
fmt.Println("查找到的结点对象为", node, ",结点值 =", node.Val)
|
2022-11-26 13:25:13 +08:00
|
|
|
|
|
|
|
// 插入结点
|
|
|
|
node = bst.Insert(16)
|
2022-12-03 20:25:24 +08:00
|
|
|
fmt.Println("插入结点后 16 的二叉树为:")
|
2022-11-26 13:25:13 +08:00
|
|
|
bst.Print()
|
|
|
|
|
|
|
|
// 删除结点
|
|
|
|
bst.Remove(1)
|
2022-12-03 20:25:24 +08:00
|
|
|
fmt.Println("删除结点 1 后的二叉树为:")
|
2022-11-26 13:25:13 +08:00
|
|
|
bst.Print()
|
|
|
|
bst.Remove(2)
|
2022-12-03 20:25:24 +08:00
|
|
|
fmt.Println("删除结点 2 后的二叉树为:")
|
2022-11-26 13:25:13 +08:00
|
|
|
bst.Print()
|
|
|
|
bst.Remove(4)
|
2022-12-03 20:25:24 +08:00
|
|
|
fmt.Println("删除结点 4 后的二叉树为:")
|
2022-11-26 13:25:13 +08:00
|
|
|
bst.Print()
|
|
|
|
}
|