Files
hello-algo/ja/codes/go/chapter_tree/array_binary_tree.go
T
Yudong Jin 7257641e0e Retranslate the complete Japanese online edition from Chinese (#2008)
* 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
2026-10-30 02:12:26 +08:00

102 lines
2.2 KiB
Go

// File: array_binary_tree.go
// Created Time: 2023-07-24
// Author: Reanon ([email protected])
package chapter_tree
/* 配列で表した二分木クラス */
type arrayBinaryTree struct {
tree []any
}
/* コンストラクタ */
func newArrayBinaryTree(arr []any) *arrayBinaryTree {
return &arrayBinaryTree{
tree: arr,
}
}
/* リストの容量 */
func (abt *arrayBinaryTree) size() int {
return len(abt.tree)
}
/* インデックス i のノードの値を取得する */
func (abt *arrayBinaryTree) val(i int) any {
// インデックスが範囲外の場合、空きを表す null を返す
if i < 0 || i >= abt.size() {
return nil
}
return abt.tree[i]
}
/* インデックス i のノードの左の子ノードのインデックスを取得する */
func (abt *arrayBinaryTree) left(i int) int {
return 2*i + 1
}
/* インデックス i のノードの右の子ノードのインデックスを取得する */
func (abt *arrayBinaryTree) right(i int) int {
return 2*i + 2
}
/* インデックス i のノードの親ノードのインデックスを取得する */
func (abt *arrayBinaryTree) parent(i int) int {
return (i - 1) / 2
}
/* レベル順走査 */
func (abt *arrayBinaryTree) levelOrder() []any {
var res []any
// 配列をそのまま走査する
for i := 0; i < abt.size(); i++ {
if abt.val(i) != nil {
res = append(res, abt.val(i))
}
}
return res
}
/* 深さ優先走査 */
func (abt *arrayBinaryTree) dfs(i int, order string, res *[]any) {
// 空きの場合、戻る
if abt.val(i) == nil {
return
}
// 行きがけ順走査
if order == "pre" {
*res = append(*res, abt.val(i))
}
abt.dfs(abt.left(i), order, res)
// 通りがけ順走査
if order == "in" {
*res = append(*res, abt.val(i))
}
abt.dfs(abt.right(i), order, res)
// 帰りがけ順走査
if order == "post" {
*res = append(*res, abt.val(i))
}
}
/* 行きがけ順走査 */
func (abt *arrayBinaryTree) preOrder() []any {
var res []any
abt.dfs(0, "pre", &res)
return res
}
/* 通りがけ順走査 */
func (abt *arrayBinaryTree) inOrder() []any {
var res []any
abt.dfs(0, "in", &res)
return res
}
/* 帰りがけ順走査 */
func (abt *arrayBinaryTree) postOrder() []any {
var res []any
abt.dfs(0, "post", &res)
return res
}