mirror of
https://github.com/krahets/hello-algo.git
synced 2025-01-23 22:40:25 +08:00
fix(tree): fix ArrToTree in go code
This commit is contained in:
parent
b73ac7bf4b
commit
33e2c4f4d3
@ -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)
|
||||
|
||||
|
@ -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)
|
||||
|
||||
|
@ -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,15 +38,19 @@ func ArrToTree(arr []int) *TreeNode {
|
||||
node := queue.Remove(queue.Front()).(*TreeNode)
|
||||
i++
|
||||
if i < len(arr) {
|
||||
node.Left = NewTreeNode(arr[i])
|
||||
if arr[i] != nil {
|
||||
node.Left = NewTreeNode(arr[i].(int))
|
||||
queue.PushBack(node.Left)
|
||||
}
|
||||
}
|
||||
i++
|
||||
if i < len(arr) {
|
||||
node.Right = NewTreeNode(arr[i])
|
||||
if arr[i] != nil {
|
||||
node.Right = NewTreeNode(arr[i].(int))
|
||||
queue.PushBack(node.Right)
|
||||
}
|
||||
}
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user