fix binary_search_tree code

This commit is contained in:
krahets
2023-08-31 02:31:31 +08:00
parent f7ab4797bf
commit 628d8a516b
14 changed files with 195 additions and 227 deletions

View File

@@ -5,8 +5,6 @@
package chapter_tree
import (
"sort"
. "github.com/krahets/hello-algo/pkg"
)
@@ -14,29 +12,13 @@ type binarySearchTree struct {
root *TreeNode
}
func newBinarySearchTree(nums []int) *binarySearchTree {
// 排序数组
sort.Ints(nums)
// 构建二叉搜索树
func newBinarySearchTree() *binarySearchTree {
bst := &binarySearchTree{}
bst.root = bst.buildTree(nums, 0, len(nums)-1)
// 初始化空树
bst.root = nil
return bst
}
/* 构建二叉搜索树 */
func (bst *binarySearchTree) buildTree(nums []int, left, right int) *TreeNode {
if left > right {
return nil
}
// 将数组中间节点作为根节点
middle := left + (right-left)>>1
root := NewTreeNode(nums[middle])
// 递归构建左子树和右子树
root.Left = bst.buildTree(nums, left, middle-1)
root.Right = bst.buildTree(nums, middle+1, right)
return root
}
/* 获取根节点 */
func (bst *binarySearchTree) getRoot() *TreeNode {
return bst.root
@@ -65,8 +47,9 @@ func (bst *binarySearchTree) search(num int) *TreeNode {
/* 插入节点 */
func (bst *binarySearchTree) insert(num int) {
cur := bst.root
// 若树为空,直接提前返回
// 若树为空,则初始化根节点
if cur == nil {
bst.root = NewTreeNode(num)
return
}
// 待插入节点之前的节点位置

View File

@@ -10,8 +10,12 @@ import (
)
func TestBinarySearchTree(t *testing.T) {
nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
bst := newBinarySearchTree(nums)
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()