From 913cf38d0bb6c0a58b49b0603436bd689ed4e3fd Mon Sep 17 00:00:00 2001 From: reanon <793584285@qq.com> Date: Sat, 26 Nov 2022 16:32:34 +0800 Subject: [PATCH] fix(tree): make go code as consistent as possible with java code --- codes/go/chapter_tree/binary_search_tree_test.go | 5 +---- codes/go/pkg/tree_node.go | 12 +++++------- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/codes/go/chapter_tree/binary_search_tree_test.go b/codes/go/chapter_tree/binary_search_tree_test.go index 45d59bd8d..955ebdbf2 100644 --- a/codes/go/chapter_tree/binary_search_tree_test.go +++ b/codes/go/chapter_tree/binary_search_tree_test.go @@ -7,7 +7,7 @@ package chapter_tree import "testing" func TestBinarySearchTree(t *testing.T) { - nums := []int{8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7} + nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} bst := NewBinarySearchTree(nums) t.Log("初始化的二叉树为: ") bst.Print() @@ -32,9 +32,6 @@ func TestBinarySearchTree(t *testing.T) { bst.Remove(1) t.Log("删除结点 1 后的二叉树为: ") bst.Print() - bst.Remove(12) - t.Log("删除结点 12 后的二叉树为: ") - bst.Print() bst.Remove(2) t.Log("删除结点 2 后的二叉树为: ") bst.Print() diff --git a/codes/go/pkg/tree_node.go b/codes/go/pkg/tree_node.go index 6175688e4..b62dc6056 100644 --- a/codes/go/pkg/tree_node.go +++ b/codes/go/pkg/tree_node.go @@ -9,9 +9,6 @@ import ( "fmt" ) -// nodeNotExist represents node don't exist. -const nodeNotExist int = -1 - type TreeNode struct { Val int Left *TreeNode @@ -54,11 +51,11 @@ func ArrayToTree(arr []int) *TreeNode { } // TreeToArray Serialize a binary tree to a list -func TreeToArray(root *TreeNode) []int { +func TreeToArray(root *TreeNode) []any { if root == nil { - return []int{} + return []any{} } - arr := make([]int, 0) + arr := make([]any, 0) queue := list.New() queue.PushBack(root) for queue.Len() > 0 { @@ -68,7 +65,8 @@ func TreeToArray(root *TreeNode) []int { queue.PushBack(node.Left) queue.PushBack(node.Right) } else { - arr = append(arr, nodeNotExist) + // node don't exist. + arr = append(arr, nil) } } return arr