mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-17 14:10:57 +00:00
Free memory after removing
a node from a LinkedList or TreeNode.
This commit is contained in:
@@ -23,13 +23,13 @@ func NewBinarySearchTree(nums []int) *BinarySearchTree {
|
||||
}
|
||||
}
|
||||
|
||||
// GetRoot Get the root node of binary search tree
|
||||
/* 获取根结点 */
|
||||
func (bst *BinarySearchTree) GetRoot() *TreeNode {
|
||||
return bst.root
|
||||
}
|
||||
|
||||
// GetMin Get node with the min value
|
||||
func (bst *BinarySearchTree) GetMin(node *TreeNode) *TreeNode {
|
||||
/* 获取中序遍历的下一个结点 */
|
||||
func (bst *BinarySearchTree) GetInOrderNext(node *TreeNode) *TreeNode {
|
||||
if node == nil {
|
||||
return node
|
||||
}
|
||||
@@ -40,19 +40,6 @@ func (bst *BinarySearchTree) GetMin(node *TreeNode) *TreeNode {
|
||||
return node
|
||||
}
|
||||
|
||||
// GetInorderNext Get node inorder next
|
||||
func (bst *BinarySearchTree) GetInorderNext(node *TreeNode) *TreeNode {
|
||||
if node == nil || node.Right == nil {
|
||||
return node
|
||||
}
|
||||
node = node.Right
|
||||
// 循环访问左子结点,直到叶结点时为最小结点,跳出
|
||||
for node.Left != nil {
|
||||
node = node.Left
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
/* 查找结点 */
|
||||
func (bst *BinarySearchTree) Search(num int) *TreeNode {
|
||||
node := bst.root
|
||||
@@ -149,7 +136,7 @@ func (bst *BinarySearchTree) Remove(num int) *TreeNode {
|
||||
// 子结点数为 2
|
||||
} else {
|
||||
// 获取中序遍历中待删除结点 cur 的下一个结点
|
||||
next := bst.GetInorderNext(cur)
|
||||
next := bst.GetInOrderNext(cur)
|
||||
temp := next.Val
|
||||
// 递归删除结点 next
|
||||
bst.Remove(next.Val)
|
||||
|
||||
@@ -12,33 +12,30 @@ 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)
|
||||
fmt.Println("初始化的二叉树为:")
|
||||
fmt.Println("\n初始化的二叉树为:")
|
||||
bst.Print()
|
||||
|
||||
// 获取根结点
|
||||
node := bst.GetRoot()
|
||||
fmt.Println("二叉树的根结点为:", node.Val)
|
||||
// 获取最小的结点
|
||||
node = bst.GetMin(bst.GetRoot())
|
||||
fmt.Println("二叉树的最小结点为:", node.Val)
|
||||
fmt.Println("\n二叉树的根结点为:", node.Val)
|
||||
|
||||
// 查找结点
|
||||
node = bst.Search(5)
|
||||
fmt.Println("查找到的结点对象为", node, ",结点值 =", node.Val)
|
||||
fmt.Println("\n查找到的结点对象为", node, ",结点值 =", node.Val)
|
||||
|
||||
// 插入结点
|
||||
node = bst.Insert(16)
|
||||
fmt.Println("插入结点后 16 的二叉树为:")
|
||||
fmt.Println("\n插入结点后 16 的二叉树为:")
|
||||
bst.Print()
|
||||
|
||||
// 删除结点
|
||||
bst.Remove(1)
|
||||
fmt.Println("删除结点 1 后的二叉树为:")
|
||||
fmt.Println("\n删除结点 1 后的二叉树为:")
|
||||
bst.Print()
|
||||
bst.Remove(2)
|
||||
fmt.Println("删除结点 2 后的二叉树为:")
|
||||
fmt.Println("\n删除结点 2 后的二叉树为:")
|
||||
bst.Print()
|
||||
bst.Remove(4)
|
||||
fmt.Println("删除结点 4 后的二叉树为:")
|
||||
fmt.Println("\n删除结点 4 后的二叉树为:")
|
||||
bst.Print()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user