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) {
|
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初始化二叉树: ")
|
fmt.Println("\n初始化二叉树: ")
|
||||||
PrintTree(root)
|
PrintTree(root)
|
||||||
|
|
||||||
|
@ -14,7 +14,7 @@ import (
|
|||||||
func TestPreInPostOrderTraversal(t *testing.T) {
|
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初始化二叉树: ")
|
fmt.Println("\n初始化二叉树: ")
|
||||||
PrintTree(root)
|
PrintTree(root)
|
||||||
|
|
||||||
|
@ -23,11 +23,12 @@ func NewTreeNode(v int) *TreeNode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ArrToTree Generate a binary tree given an array
|
// ArrToTree Generate a binary tree given an array
|
||||||
func ArrToTree(arr []int) *TreeNode {
|
func ArrToTree(arr []any) *TreeNode {
|
||||||
if len(arr) <= 0 {
|
if len(arr) <= 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
root := NewTreeNode(arr[0])
|
// TreeNode only accept integer value for now.
|
||||||
|
root := NewTreeNode(arr[0].(int))
|
||||||
// Let container.list as queue
|
// Let container.list as queue
|
||||||
queue := list.New()
|
queue := list.New()
|
||||||
queue.PushBack(root)
|
queue.PushBack(root)
|
||||||
@ -37,13 +38,17 @@ func ArrToTree(arr []int) *TreeNode {
|
|||||||
node := queue.Remove(queue.Front()).(*TreeNode)
|
node := queue.Remove(queue.Front()).(*TreeNode)
|
||||||
i++
|
i++
|
||||||
if i < len(arr) {
|
if i < len(arr) {
|
||||||
node.Left = NewTreeNode(arr[i])
|
if arr[i] != nil {
|
||||||
queue.PushBack(node.Left)
|
node.Left = NewTreeNode(arr[i].(int))
|
||||||
|
queue.PushBack(node.Left)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
i++
|
i++
|
||||||
if i < len(arr) {
|
if i < len(arr) {
|
||||||
node.Right = NewTreeNode(arr[i])
|
if arr[i] != nil {
|
||||||
queue.PushBack(node.Right)
|
node.Right = NewTreeNode(arr[i].(int))
|
||||||
|
queue.PushBack(node.Right)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return root
|
return root
|
||||||
|
@ -10,7 +10,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestTreeNode(t *testing.T) {
|
func TestTreeNode(t *testing.T) {
|
||||||
arr := []int{2, 3, 5, 6, 7}
|
arr := []any{1, 2, 3, nil, 5, 6, nil}
|
||||||
node := ArrToTree(arr)
|
node := ArrToTree(arr)
|
||||||
|
|
||||||
// print tree
|
// print tree
|
||||||
|
Loading…
Reference in New Issue
Block a user