Back to Repositories

Testing Binary Search Tree Operations in hello-algo

This test suite validates the implementation of a Binary Search Tree (BST) in Go, covering essential operations like insertion, deletion, and search functionality. The tests ensure proper tree construction and manipulation while maintaining BST properties.

Test Coverage Overview

The test suite provides comprehensive coverage of Binary Search Tree operations:
  • Tree initialization and node insertion sequence validation
  • Root node access and verification
  • Node search functionality testing
  • Dynamic node insertion validation
  • Complex deletion scenarios with tree rebalancing

Implementation Analysis

The testing approach utilizes Go’s native testing framework with a focus on sequential operation verification. The test structure demonstrates systematic validation of BST operations, employing a predefined sequence of numbers to create a balanced tree structure.

The implementation leverages Go’s testing.T framework for assertion handling and fmt for visual verification output.

Technical Details

Testing Framework Components:
  • Go testing package (testing.T)
  • fmt package for output formatting
  • Custom BST implementation with newBinarySearchTree()
  • Structured test data with predefined number sequence

Best Practices Demonstrated

The test suite exemplifies several testing best practices:
  • Systematic operation sequencing
  • Visual state verification after operations
  • Comprehensive edge case coverage
  • Clear test case organization
  • Proper setup and initialization patterns

krahets/hello-algo

zh-hant/codes/go/chapter_tree/binary_search_tree_test.go

            
// File: binary_search_tree_test.go
// Created Time: 2022-11-26
// Author: Reanon ([email protected])

package chapter_tree

import (
	"fmt"
	"testing"
)

func TestBinarySearchTree(t *testing.T) {
	bst := newBinarySearchTree()
	nums := []int{8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15}
	// 請注意,不同的插入順序會生成不同的二元樹,該序列可以生成一個完美二元樹
	for _, num := range nums {
		bst.insert(num)
	}
	fmt.Println("\n初始化的二元樹為:")
	bst.print()

	// 獲取根節點
	node := bst.getRoot()
	fmt.Println("\n二元樹的根節點為:", node.Val)

	// 查詢節點
	node = bst.search(7)
	fmt.Println("查詢到的節點物件為", node, ",節點值 =", node.Val)

	// 插入節點
	bst.insert(16)
	fmt.Println("\n插入節點後 16 的二元樹為:")
	bst.print()

	// 刪除節點
	bst.remove(1)
	fmt.Println("\n刪除節點 1 後的二元樹為:")
	bst.print()
	bst.remove(2)
	fmt.Println("\n刪除節點 2 後的二元樹為:")
	bst.print()
	bst.remove(4)
	fmt.Println("\n刪除節點 4 後的二元樹為:")
	bst.print()
}