mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-02 03:05:24 +08:00
* Retranslate the complete Japanese online edition from Chinese * Fit Japanese homepage labels and localize heading permalinks * Point Japanese contribution instructions to the Japanese preview * Replace locale conditionals with multilingual UI tables
48 lines
1.4 KiB
Go
48 lines
1.4 KiB
Go
// File: array_binary_tree_test.go
|
|
// Created Time: 2023-07-24
|
|
// Author: Reanon ([email protected])
|
|
|
|
package chapter_tree
|
|
|
|
import (
|
|
"fmt"
|
|
"testing"
|
|
|
|
. "github.com/krahets/hello-algo/pkg"
|
|
)
|
|
|
|
func TestArrayBinaryTree(t *testing.T) {
|
|
// 二分木を初期化する
|
|
// ここでは配列から二分木を直接生成する関数を使う
|
|
arr := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15}
|
|
root := SliceToTree(arr)
|
|
fmt.Println("\n二分木を初期化する")
|
|
fmt.Println("二分木の配列表現:")
|
|
fmt.Println(arr)
|
|
fmt.Println("二分木の連結リスト表現:")
|
|
PrintTree(root)
|
|
|
|
// 配列で表した二分木クラス
|
|
abt := newArrayBinaryTree(arr)
|
|
|
|
// ノードにアクセスする
|
|
i := 1
|
|
l := abt.left(i)
|
|
r := abt.right(i)
|
|
p := abt.parent(i)
|
|
fmt.Println("\n現在のノードのインデックスは", i, "、値は", abt.val(i))
|
|
fmt.Println("左の子ノードのインデックスは", l, "、値は", abt.val(l))
|
|
fmt.Println("右の子ノードのインデックスは", r, "、値は", abt.val(r))
|
|
fmt.Println("親ノードのインデックスは", p, "、値は", abt.val(p))
|
|
|
|
// 木を走査する
|
|
res := abt.levelOrder()
|
|
fmt.Println("\nレベル順走査:", res)
|
|
res = abt.preOrder()
|
|
fmt.Println("行きがけ順走査:", res)
|
|
res = abt.inOrder()
|
|
fmt.Println("通りがけ順走査:", res)
|
|
res = abt.postOrder()
|
|
fmt.Println("帰りがけ順走査:", res)
|
|
}
|