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}
|
2023-01-03 14:39:31 +08:00
|
|
|
bst := newBinarySearchTree(nums)
|
2023-01-02 19:53:55 +08:00
|
|
|
fmt.Println("\n初始化的二叉树为:")
|
2023-01-03 14:39:31 +08:00
|
|
|
bst.print()
|
2022-11-26 13:25:13 +08:00
|
|
|
|
2023-04-09 04:32:17 +08:00
|
|
|
// 获取根节点
|
2023-01-03 14:39:31 +08:00
|
|
|
node := bst.getRoot()
|
2023-04-09 04:32:17 +08:00
|
|
|
fmt.Println("\n二叉树的根节点为:", node.Val)
|
2022-11-26 13:25:13 +08:00
|
|
|
|
2023-04-09 04:32:17 +08:00
|
|
|
// 查找节点
|
2023-01-11 01:56:08 +08:00
|
|
|
node = bst.search(7)
|
2023-04-09 04:32:17 +08:00
|
|
|
fmt.Println("查找到的节点对象为", node, ",节点值 =", node.Val)
|
2022-11-26 13:25:13 +08:00
|
|
|
|
2023-04-09 04:32:17 +08:00
|
|
|
// 插入节点
|
2023-01-03 14:39:31 +08:00
|
|
|
node = bst.insert(16)
|
2023-04-09 04:32:17 +08:00
|
|
|
fmt.Println("\n插入节点后 16 的二叉树为:")
|
2023-01-03 14:39:31 +08:00
|
|
|
bst.print()
|
2022-11-26 13:25:13 +08:00
|
|
|
|
2023-04-09 04:32:17 +08:00
|
|
|
// 删除节点
|
2023-01-03 14:39:31 +08:00
|
|
|
bst.remove(1)
|
2023-04-09 04:32:17 +08:00
|
|
|
fmt.Println("\n删除节点 1 后的二叉树为:")
|
2023-01-03 14:39:31 +08:00
|
|
|
bst.print()
|
|
|
|
bst.remove(2)
|
2023-04-09 04:32:17 +08:00
|
|
|
fmt.Println("\n删除节点 2 后的二叉树为:")
|
2023-01-03 14:39:31 +08:00
|
|
|
bst.print()
|
|
|
|
bst.remove(4)
|
2023-04-09 04:32:17 +08:00
|
|
|
fmt.Println("\n删除节点 4 后的二叉树为:")
|
2023-01-03 14:39:31 +08:00
|
|
|
bst.print()
|
2022-11-26 13:25:13 +08:00
|
|
|
}
|