2022-11-25 20:24:51 +08:00
|
|
|
// File: tree_node.go
|
|
|
|
// Created Time: 2022-11-25
|
|
|
|
// Author: Reanon (793584285@qq.com)
|
|
|
|
|
|
|
|
package pkg
|
|
|
|
|
|
|
|
import (
|
|
|
|
"container/list"
|
|
|
|
)
|
|
|
|
|
|
|
|
type TreeNode struct {
|
|
|
|
Val int
|
|
|
|
Left *TreeNode
|
|
|
|
Right *TreeNode
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewTreeNode(v int) *TreeNode {
|
|
|
|
return &TreeNode{
|
|
|
|
Left: nil,
|
|
|
|
Right: nil,
|
|
|
|
Val: v,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-08 19:03:22 +08:00
|
|
|
// ArrToTree Generate a binary tree given an array
|
2023-01-08 20:00:36 +08:00
|
|
|
func ArrToTree(arr []any) *TreeNode {
|
2022-11-25 20:24:51 +08:00
|
|
|
if len(arr) <= 0 {
|
|
|
|
return nil
|
|
|
|
}
|
2023-01-08 20:00:36 +08:00
|
|
|
// TreeNode only accept integer value for now.
|
|
|
|
root := NewTreeNode(arr[0].(int))
|
2022-11-25 20:24:51 +08:00
|
|
|
// Let container.list as queue
|
|
|
|
queue := list.New()
|
|
|
|
queue.PushBack(root)
|
2023-01-08 19:03:22 +08:00
|
|
|
i := 0
|
2022-11-25 20:24:51 +08:00
|
|
|
for queue.Len() > 0 {
|
|
|
|
// poll
|
|
|
|
node := queue.Remove(queue.Front()).(*TreeNode)
|
2023-01-08 19:03:22 +08:00
|
|
|
i++
|
2022-11-25 20:24:51 +08:00
|
|
|
if i < len(arr) {
|
2023-01-08 20:00:36 +08:00
|
|
|
if arr[i] != nil {
|
|
|
|
node.Left = NewTreeNode(arr[i].(int))
|
|
|
|
queue.PushBack(node.Left)
|
|
|
|
}
|
2022-11-25 20:24:51 +08:00
|
|
|
}
|
2023-01-08 19:03:22 +08:00
|
|
|
i++
|
2022-11-25 20:24:51 +08:00
|
|
|
if i < len(arr) {
|
2023-01-08 20:00:36 +08:00
|
|
|
if arr[i] != nil {
|
|
|
|
node.Right = NewTreeNode(arr[i].(int))
|
|
|
|
queue.PushBack(node.Right)
|
|
|
|
}
|
2022-11-25 20:24:51 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return root
|
|
|
|
}
|
|
|
|
|
|
|
|
// TreeToArray Serialize a binary tree to a list
|
2022-11-26 16:32:34 +08:00
|
|
|
func TreeToArray(root *TreeNode) []any {
|
2022-11-25 20:24:51 +08:00
|
|
|
if root == nil {
|
2022-11-26 16:32:34 +08:00
|
|
|
return []any{}
|
2022-11-25 20:24:51 +08:00
|
|
|
}
|
2022-11-26 16:32:34 +08:00
|
|
|
arr := make([]any, 0)
|
2022-11-25 20:24:51 +08:00
|
|
|
queue := list.New()
|
|
|
|
queue.PushBack(root)
|
|
|
|
for queue.Len() > 0 {
|
|
|
|
node := queue.Remove(queue.Front()).(*TreeNode)
|
|
|
|
if node != nil {
|
|
|
|
arr = append(arr, node.Val)
|
|
|
|
queue.PushBack(node.Left)
|
|
|
|
queue.PushBack(node.Right)
|
|
|
|
} else {
|
2022-11-26 16:32:34 +08:00
|
|
|
// node don't exist.
|
|
|
|
arr = append(arr, nil)
|
2022-11-25 20:24:51 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return arr
|
|
|
|
}
|