fix(tree): fix ArrToTree in go code

This commit is contained in:
reanon 2023-01-08 20:00:36 +08:00
parent b73ac7bf4b
commit 33e2c4f4d3
4 changed files with 14 additions and 9 deletions

View File

@ -14,7 +14,7 @@ import (
func TestLevelOrder(t *testing.T) {
/* 初始化二叉树 */
// 这里借助了一个从数组直接生成二叉树的函数
root := ArrToTree([]int{1, 2, 3, 4, 5, 6, 7})
root := ArrToTree([]any{1, 2, 3, 4, 5, 6, 7})
fmt.Println("\n初始化二叉树: ")
PrintTree(root)

View File

@ -14,7 +14,7 @@ import (
func TestPreInPostOrderTraversal(t *testing.T) {
/* 初始化二叉树 */
// 这里借助了一个从数组直接生成二叉树的函数
root := ArrToTree([]int{1, 2, 3, 4, 5, 6, 7})
root := ArrToTree([]any{1, 2, 3, 4, 5, 6, 7})
fmt.Println("\n初始化二叉树: ")
PrintTree(root)

View File

@ -23,11 +23,12 @@ func NewTreeNode(v int) *TreeNode {
}
// ArrToTree Generate a binary tree given an array
func ArrToTree(arr []int) *TreeNode {
func ArrToTree(arr []any) *TreeNode {
if len(arr) <= 0 {
return nil
}
root := NewTreeNode(arr[0])
// TreeNode only accept integer value for now.
root := NewTreeNode(arr[0].(int))
// Let container.list as queue
queue := list.New()
queue.PushBack(root)
@ -37,13 +38,17 @@ func ArrToTree(arr []int) *TreeNode {
node := queue.Remove(queue.Front()).(*TreeNode)
i++
if i < len(arr) {
node.Left = NewTreeNode(arr[i])
queue.PushBack(node.Left)
if arr[i] != nil {
node.Left = NewTreeNode(arr[i].(int))
queue.PushBack(node.Left)
}
}
i++
if i < len(arr) {
node.Right = NewTreeNode(arr[i])
queue.PushBack(node.Right)
if arr[i] != nil {
node.Right = NewTreeNode(arr[i].(int))
queue.PushBack(node.Right)
}
}
}
return root

View File

@ -10,7 +10,7 @@ import (
)
func TestTreeNode(t *testing.T) {
arr := []int{2, 3, 5, 6, 7}
arr := []any{1, 2, 3, nil, 5, 6, nil}
node := ArrToTree(arr)
// print tree