コンテンツにスキップ

7.3   二分木の配列表現

連結表現では、二分木の記憶単位はノード TreeNode で、ノード同士はポインタでつながっています。前節では、この表現を用いた二分木の基本操作を紹介しました。

では、二分木を配列で表すこともできるでしょうか。答えは「はい」です。

7.3.1   完璧二分木の表現

まず簡単な例を考えましょう。完璧二分木のすべてのノードをレベル順に配列に格納すると、各ノードに配列のインデックスが一つずつ対応します。

レベル順走査の性質から、親と子のインデックスの対応を表す式を導けます。あるノードのインデックスが \(i\) なら、左の子のインデックスは \(2i + 1\)、右の子のインデックスは \(2i + 2\) です。図 7-12 に各ノードのインデックスの対応を示します。

図 7-12   完璧二分木の配列表現

図解 7-12:すべての層が埋まった二分木の配列表現

すべての層が埋まった二分木を添字が 0 から始まる配列にレベル順で格納し、添字の式 2i+1 と 2i+2 から左右の子を求めます。

4 層すべてが埋まった二分木には 15 個のノードがあり、値はレベル順に 1 から 15 です。第 1 層の根は 1、第 2 層は 2 と 3、第 3 層は 4 から 7、第 4 層の葉は 8 から 15 です。この順で配列のインデックス 0 から 14 に格納します。各ノードのインデックスと左右の子の位置を表に示します。

ノードのインデックスと左右の子の位置
現在のインデックスノードの値左の子のインデックスと値右の子のインデックスと値
011:22:3
123:44:5
235:66:7
347:88:9
459:1010:11
5611:1212:13
6713:1414:15
7815:範囲外、子なし16:範囲外、子なし
8917:範囲外、子なし18:範囲外、子なし
91019:範囲外、子なし20:範囲外、子なし
101121:範囲外、子なし22:範囲外、子なし
111223:範囲外、子なし24:範囲外、子なし
121325:範囲外、子なし26:範囲外、子なし
131427:範囲外、子なし28:範囲外、子なし
141529:範囲外、子なし30:範囲外、子なし

式に代入する i は、ノードの値ではなく配列のインデックスです。例えばノード 6 のインデックスは 5 です。その左の子はインデックス 11(値 12)、右の子はインデックス 12(値 13)にあります。

インデックスの計算式で子へのポインタを置き換えられますが、アクセス時には配列の範囲を確認する必要があります。図のインデックス 7 から 14(ノード 8 から 15)は葉です。計算で求めた子の位置 15 から 30 はすべて範囲外で、子が存在しないことを示します。

この式は、連結表現におけるノードへの参照(ポインタ)と同じ役割を果たします。配列内のどのノードからでも、式を使って左右の子にアクセスできます。

7.3.2   任意の二分木の表現

完璧二分木は特別な例です。一般の二分木では、途中の層に多くの None があります。レベル順の走査列にはこれらの None が含まれないため、列だけから None の個数や位置を割り出すことはできません。つまり、同じレベル順の走査列に複数の木の形が対応し得ます。

図 7-13 のように、完璧二分木でない木では、先ほどの配列表現はうまくいきません。

図 7-13   同じレベル順の走査列に対応する複数の二分木

図解 7-13:途中の空きを省いたレベル順の配列

木の途中の空きを省いてレベル順の配列を詰めると、インデックスがずれます。同じ値の列が異なる木の形に対応し得ます。

表の「元の木の位置番号」は、空きを残して根を 0 としてレベル順に振った番号です。「詰めた後のインデックス」は空きを飛ばした配列のインデックスです。図に描かれているのは次の元の木だけです。

元の木には 10 個のノードがあります。根は 1(位置 0)、左右の子は 2(位置 1)と 3(位置 2)です。2 の子は左の 4(位置 3)だけです。3 の左右の子は 6(位置 5)と 7(位置 6)、4 の左右の子は 8(位置 7)と 9(位置 8)です。6 の子は左の 12(位置 11)だけ、7 の子は右の 15(位置 14)だけです。8、9、12、15 は葉です。詰めた配列のインデックス 0~9 と元の位置番号の対応を下表に示します。

詰めた配列と元の木の位置の対応
詰めた配列のインデックスノードの値元の木の位置番号
010
121
232
343
465
576
687
798
81211
91514

元の木では位置 4、9、10、12、13 にノードがありません。空きを飛ばして [1, 2, 3, 4, 6, 7, 8, 9, 12, 15] と詰めると、ノード 6 は元の位置 5 からインデックス 4 に移ります。ここで 2i+2 を使うと、インデックス 4 の 6 がインデックス 1 のノード 2 の右の子だと誤認されます。元の木では 2 に右の子はなく、6 は 3 の左の子です。詰めた配列に式を当てはめて別の木を導くと、1 の左右の子は 2 と 3、2 の左右の子は 4 と 6、3 の左右の子は 7 と 8、4 の左右の子は 9 と 12 です。6 は左の子 15 だけを持ち、残りは葉です。元の木とはつながり方が異なりますが、レベル順の値の列は同じです。この比較用の木は式から導いたもので、図には描かれていません。

途中の空きを省くと、同じレベル順の値の列が、つながり方の異なる木に対応し得ます。これは途中に空きがある場合の問題です。完全二分木の空きはレベル順の末尾に集まるため、省略してもインデックスの対応は保たれます。

この問題を解決するには、レベル順の走査列にすべての None を明示する方法があります。こうすれば、図 7-14 のようにレベル順の列から二分木が一意に定まります。コード例を示します。

# 二分木の配列表現
# 空きを None で表す
tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15]
/* 二分木の配列表現 */
// 空きを int の最大値 INT_MAX で表す
vector<int> tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15};
/* 二分木の配列表現 */
// int のラッパークラス Integer を使えば、空きを null で表せる
Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 };
/* 二分木の配列表現 */
// null 許容型 int? を使えば、空きを null で表せる
int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
/* 二分木の配列表現 */
// 要素型が any のスライスを使えば、空きを nil で表せる
tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15}
/* 二分木の配列表現 */
// nil を許容する Int? 型を使えば、空きを nil で表せる
let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15]
/* 二分木の配列表現 */
// 空きを null で表す
let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
/* 二分木の配列表現 */
// 空きを null で表す
let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
/* 二分木の配列表現 */
// null 許容型 int? を使えば、空きを null で表せる
List<int?> tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
/* 二分木の配列表現 */
// 空きを None で表す
let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)];
/* 二分木の配列表現 */
// 空きを int の最大値で表すので、ノードの値には INT_MAX を使えない
int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15};
/* 二分木の配列表現 */
// 空きを null で表す
val tree = arrayOf( 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 )
### 二分木の配列表現 ###
# 空きを nil で表す
tree = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15]

図 7-14   任意の二分木の配列表現

図解 7-14:空きを残した二分木の配列

レベル順の配列で途中の欠けたノードの位置を明示的に空けておくと、2i+1 と 2i+2 の対応から木の形を一意に復元できます。

塗りつぶした 10 個のノードの接続は次のとおりです。根 1 の左右の子は 2 と 3、2 の子は左の 4 だけ、3 の左右の子は 6 と 7、4 の左右の子は 8 と 9 です。6 の子は左の 12 だけ、7 の子は右の 15 だけで、8、9、12、15 は葉です。配列のインデックス 0~14 の計 15 枠には 10 個の値が入り、4、9、10、12、13 の 5 枠は空きです。各枠の内容を下表に示します。

配列のインデックスとノードの値
インデックスノードの値または空き
01
12
23
34
4空き
56
67
78
89
9空き
10空き
1112
12空き
13空き
1415

インデックス 4 にはノードがありませんが、それに対応する次の層の子の位置 9 と 10 も空けておく必要があります。こうすると、後続のノードが前にずれません。例えばインデックス 5 のノード 6 は、左の子の位置 11 に 12 があり、右の子の位置 12 は空いています。

途中の空きを明示しておくと、インデックス i の子の位置 2i+1、2i+2 から、この木を一意に復元できます。空きはその位置にノードがないことを表し、コードではよく None や null と記します。値 0 とは区別します。

特に、完全二分木は配列表現に適しています。定義を振り返ると、完全二分木で None が現れるのは最下層の右端だけです。したがって、すべての None はレベル順の走査列の末尾に集まります。

このため、完全二分木を配列で表す際には、None をすべて省略できて便利です。図 7-15 に例を示します。

図 7-15   完全二分木の配列表現

図解 7-15:完全二分木の配列表現では末尾の空きを省略できる

完全二分木の空きはレベル順の配列の末尾に集まるため、省略しても既存のノードのインデックスは変わりません。

完全二分木では最下層以外がすべて埋まり、最下層のノードは必ず左から隙間なく並びます。図の配列は 0 始まりで、実際に存在する 10 個のノードはインデックス 0~9 を占めます。

左の 4 層の完全二分木には、塗りつぶしたノードが 10 個あります。根 1 の左右の子は 2 と 3、2 の左右の子は 4 と 5、3 の左右の子は 6 と 7、4 の左右の子は 8 と 9 です。5 の子は左の 10 だけで、6、7、8、9、10 は葉です。第 4 層の 10 の右に、灰色の破線で描いた白抜きの円が 5 個並び、末尾の空きを示しています。

右上の「レベル順の走査列(配列)」には、[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] に続く 5 個の空きが破線の枠で描かれています。中央の下向き矢印と灰色の説明枠「完全二分木では空きを格納しなくてもよい」が、右下の最終的な配列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] を指します。省いた 5 個の空きはすべて末尾にあるので、先頭の 10 個のノードのインデックスは変わりません。

例えばインデックス 4 にあるノード 5 の左の子の位置は 2×4+1 = 9 で、そこにノード 10 があります。右の子の位置 2×4+2 = 10 は長さ 10 の配列の範囲外なので、右の子はありません。

末尾の空きを省いても 2i+1 と 2i+2 の対応は成り立ちます。計算した子の位置にアクセスする際には、配列の範囲を確認します。

次のコードは、配列を使った二分木の実装です。以下の操作に対応しています。

  • 指定したノードの値、左右の子、親を取得します。
  • 行きがけ順、通りがけ順、帰りがけ順、レベル順の走査列を取得します。
array_binary_tree.py
class ArrayBinaryTree:
    """二分木を配列で表すクラス"""

    def __init__(self, arr: list[int | None]):
        """コンストラクタ"""
        self._tree = list(arr)

    def size(self):
        """リストの容量"""
        return len(self._tree)

    def val(self, i: int) -> int | None:
        """インデックス i のノードの値を取得する"""
        # 範囲外なら空きを示す None を返す
        if i < 0 or i >= self.size():
            return None
        return self._tree[i]

    def left(self, i: int) -> int | None:
        """インデックス i のノードの左の子のインデックスを取得する"""
        return 2 * i + 1

    def right(self, i: int) -> int | None:
        """インデックス i のノードの右の子のインデックスを取得する"""
        return 2 * i + 2

    def parent(self, i: int) -> int | None:
        """インデックス i のノードの親のインデックスを取得する"""
        return (i - 1) // 2

    def level_order(self) -> list[int]:
        """レベル順走査"""
        self.res = []
        # 配列を順に走査する
        for i in range(self.size()):
            if self.val(i) is not None:
                self.res.append(self.val(i))
        return self.res

    def dfs(self, i: int, order: str):
        """深さ優先走査"""
        if self.val(i) is None:
            return
        # 行きがけ順走査
        if order == "pre":
            self.res.append(self.val(i))
        self.dfs(self.left(i), order)
        # 通りがけ順走査
        if order == "in":
            self.res.append(self.val(i))
        self.dfs(self.right(i), order)
        # 帰りがけ順走査
        if order == "post":
            self.res.append(self.val(i))

    def pre_order(self) -> list[int]:
        """行きがけ順走査"""
        self.res = []
        self.dfs(0, order="pre")
        return self.res

    def in_order(self) -> list[int]:
        """通りがけ順走査"""
        self.res = []
        self.dfs(0, order="in")
        return self.res

    def post_order(self) -> list[int]:
        """帰りがけ順走査"""
        self.res = []
        self.dfs(0, order="post")
        return self.res
array_binary_tree.cpp
/* 二分木を配列で表すクラス */
class ArrayBinaryTree {
  public:
    /* コンストラクタ */
    ArrayBinaryTree(vector<int> arr) {
        tree = arr;
    }

    /* リストの容量 */
    int size() {
        return tree.size();
    }

    /* インデックス i のノードの値を取得する */
    int val(int i) {
        // 範囲外なら空きを示す INT_MAX を返す
        if (i < 0 || i >= size())
            return INT_MAX;
        return tree[i];
    }

    /* インデックス i のノードの左の子のインデックスを取得する */
    int left(int i) {
        return 2 * i + 1;
    }

    /* インデックス i のノードの右の子のインデックスを取得する */
    int right(int i) {
        return 2 * i + 2;
    }

    /* インデックス i のノードの親のインデックスを取得する */
    int parent(int i) {
        return (i - 1) / 2;
    }

    /* レベル順走査 */
    vector<int> levelOrder() {
        vector<int> res;
        // 配列を順に走査する
        for (int i = 0; i < size(); i++) {
            if (val(i) != INT_MAX)
                res.push_back(val(i));
        }
        return res;
    }

    /* 行きがけ順走査 */
    vector<int> preOrder() {
        vector<int> res;
        dfs(0, "pre", res);
        return res;
    }

    /* 通りがけ順走査 */
    vector<int> inOrder() {
        vector<int> res;
        dfs(0, "in", res);
        return res;
    }

    /* 帰りがけ順走査 */
    vector<int> postOrder() {
        vector<int> res;
        dfs(0, "post", res);
        return res;
    }

  private:
    vector<int> tree;

    /* 深さ優先走査 */
    void dfs(int i, string order, vector<int> &res) {
        // 空きなら戻る
        if (val(i) == INT_MAX)
            return;
        // 行きがけ順走査
        if (order == "pre")
            res.push_back(val(i));
        dfs(left(i), order, res);
        // 通りがけ順走査
        if (order == "in")
            res.push_back(val(i));
        dfs(right(i), order, res);
        // 帰りがけ順走査
        if (order == "post")
            res.push_back(val(i));
    }
};
array_binary_tree.java
/* 二分木を配列で表すクラス */
class ArrayBinaryTree {
    private List<Integer> tree;

    /* コンストラクタ */
    public ArrayBinaryTree(List<Integer> arr) {
        tree = new ArrayList<>(arr);
    }

    /* リストの容量 */
    public int size() {
        return tree.size();
    }

    /* インデックス i のノードの値を取得する */
    public Integer val(int i) {
        // 範囲外なら空きを示す null を返す
        if (i < 0 || i >= size())
            return null;
        return tree.get(i);
    }

    /* インデックス i のノードの左の子のインデックスを取得する */
    public Integer left(int i) {
        return 2 * i + 1;
    }

    /* インデックス i のノードの右の子のインデックスを取得する */
    public Integer right(int i) {
        return 2 * i + 2;
    }

    /* インデックス i のノードの親のインデックスを取得する */
    public Integer parent(int i) {
        return (i - 1) / 2;
    }

    /* レベル順走査 */
    public List<Integer> levelOrder() {
        List<Integer> res = new ArrayList<>();
        // 配列を順に走査する
        for (int i = 0; i < size(); i++) {
            if (val(i) != null)
                res.add(val(i));
        }
        return res;
    }

    /* 深さ優先走査 */
    private void dfs(Integer i, String order, List<Integer> res) {
        // 空きなら戻る
        if (val(i) == null)
            return;
        // 行きがけ順走査
        if ("pre".equals(order))
            res.add(val(i));
        dfs(left(i), order, res);
        // 通りがけ順走査
        if ("in".equals(order))
            res.add(val(i));
        dfs(right(i), order, res);
        // 帰りがけ順走査
        if ("post".equals(order))
            res.add(val(i));
    }

    /* 行きがけ順走査 */
    public List<Integer> preOrder() {
        List<Integer> res = new ArrayList<>();
        dfs(0, "pre", res);
        return res;
    }

    /* 通りがけ順走査 */
    public List<Integer> inOrder() {
        List<Integer> res = new ArrayList<>();
        dfs(0, "in", res);
        return res;
    }

    /* 帰りがけ順走査 */
    public List<Integer> postOrder() {
        List<Integer> res = new ArrayList<>();
        dfs(0, "post", res);
        return res;
    }
}
array_binary_tree.cs
/* 二分木を配列で表すクラス */
class ArrayBinaryTree(List<int?> arr) {
    List<int?> tree = new(arr);

    /* リストの容量 */
    public int Size() {
        return tree.Count;
    }

    /* インデックス i のノードの値を取得する */
    public int? Val(int i) {
        // 範囲外なら空きを示す null を返す
        if (i < 0 || i >= Size())
            return null;
        return tree[i];
    }

    /* インデックス i のノードの左の子のインデックスを取得する */
    public int Left(int i) {
        return 2 * i + 1;
    }

    /* インデックス i のノードの右の子のインデックスを取得する */
    public int Right(int i) {
        return 2 * i + 2;
    }

    /* インデックス i のノードの親のインデックスを取得する */
    public int Parent(int i) {
        return (i - 1) / 2;
    }

    /* レベル順走査 */
    public List<int> LevelOrder() {
        List<int> res = [];
        // 配列を順に走査する
        for (int i = 0; i < Size(); i++) {
            if (Val(i).HasValue)
                res.Add(Val(i)!.Value);
        }
        return res;
    }

    /* 深さ優先走査 */
    void DFS(int i, string order, List<int> res) {
        // 空きなら戻る
        if (!Val(i).HasValue)
            return;
        // 行きがけ順走査
        if (order == "pre")
            res.Add(Val(i)!.Value);
        DFS(Left(i), order, res);
        // 通りがけ順走査
        if (order == "in")
            res.Add(Val(i)!.Value);
        DFS(Right(i), order, res);
        // 帰りがけ順走査
        if (order == "post")
            res.Add(Val(i)!.Value);
    }

    /* 行きがけ順走査 */
    public List<int> PreOrder() {
        List<int> res = [];
        DFS(0, "pre", res);
        return res;
    }

    /* 通りがけ順走査 */
    public List<int> InOrder() {
        List<int> res = [];
        DFS(0, "in", res);
        return res;
    }

    /* 帰りがけ順走査 */
    public List<int> PostOrder() {
        List<int> res = [];
        DFS(0, "post", res);
        return res;
    }
}
array_binary_tree.go
/* 二分木を配列で表すクラス */
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
}
array_binary_tree.swift
/* 二分木を配列で表すクラス */
class ArrayBinaryTree {
    private var tree: [Int?]

    /* コンストラクタ */
    init(arr: [Int?]) {
        tree = arr
    }

    /* リストの容量 */
    func size() -> Int {
        tree.count
    }

    /* インデックス i のノードの値を取得する */
    func val(i: Int) -> Int? {
        // 範囲外なら空きを示す null を返す
        if i < 0 || i >= size() {
            return nil
        }
        return tree[i]
    }

    /* インデックス i のノードの左の子のインデックスを取得する */
    func left(i: Int) -> Int {
        2 * i + 1
    }

    /* インデックス i のノードの右の子のインデックスを取得する */
    func right(i: Int) -> Int {
        2 * i + 2
    }

    /* インデックス i のノードの親のインデックスを取得する */
    func parent(i: Int) -> Int {
        (i - 1) / 2
    }

    /* レベル順走査 */
    func levelOrder() -> [Int] {
        var res: [Int] = []
        // 配列を順に走査する
        for i in 0 ..< size() {
            if let val = val(i: i) {
                res.append(val)
            }
        }
        return res
    }

    /* 深さ優先走査 */
    private func dfs(i: Int, order: String, res: inout [Int]) {
        // 空きなら戻る
        guard let val = val(i: i) else {
            return
        }
        // 行きがけ順走査
        if order == "pre" {
            res.append(val)
        }
        dfs(i: left(i: i), order: order, res: &res)
        // 通りがけ順走査
        if order == "in" {
            res.append(val)
        }
        dfs(i: right(i: i), order: order, res: &res)
        // 帰りがけ順走査
        if order == "post" {
            res.append(val)
        }
    }

    /* 行きがけ順走査 */
    func preOrder() -> [Int] {
        var res: [Int] = []
        dfs(i: 0, order: "pre", res: &res)
        return res
    }

    /* 通りがけ順走査 */
    func inOrder() -> [Int] {
        var res: [Int] = []
        dfs(i: 0, order: "in", res: &res)
        return res
    }

    /* 帰りがけ順走査 */
    func postOrder() -> [Int] {
        var res: [Int] = []
        dfs(i: 0, order: "post", res: &res)
        return res
    }
}
array_binary_tree.js
/* 二分木を配列で表すクラス */
class ArrayBinaryTree {
    #tree;

    /* コンストラクタ */
    constructor(arr) {
        this.#tree = arr;
    }

    /* リストの容量 */
    size() {
        return this.#tree.length;
    }

    /* インデックス i のノードの値を取得する */
    val(i) {
        // 範囲外なら空きを示す null を返す
        if (i < 0 || i >= this.size()) return null;
        return this.#tree[i];
    }

    /* インデックス i のノードの左の子のインデックスを取得する */
    left(i) {
        return 2 * i + 1;
    }

    /* インデックス i のノードの右の子のインデックスを取得する */
    right(i) {
        return 2 * i + 2;
    }

    /* インデックス i のノードの親のインデックスを取得する */
    parent(i) {
        return Math.floor((i - 1) / 2); // 商を負の無限大の方向に切り下げる
    }

    /* レベル順走査 */
    levelOrder() {
        let res = [];
        // 配列を順に走査する
        for (let i = 0; i < this.size(); i++) {
            if (this.val(i) !== null) res.push(this.val(i));
        }
        return res;
    }

    /* 深さ優先走査 */
    #dfs(i, order, res) {
        // 空きなら戻る
        if (this.val(i) === null) return;
        // 行きがけ順走査
        if (order === 'pre') res.push(this.val(i));
        this.#dfs(this.left(i), order, res);
        // 通りがけ順走査
        if (order === 'in') res.push(this.val(i));
        this.#dfs(this.right(i), order, res);
        // 帰りがけ順走査
        if (order === 'post') res.push(this.val(i));
    }

    /* 行きがけ順走査 */
    preOrder() {
        const res = [];
        this.#dfs(0, 'pre', res);
        return res;
    }

    /* 通りがけ順走査 */
    inOrder() {
        const res = [];
        this.#dfs(0, 'in', res);
        return res;
    }

    /* 帰りがけ順走査 */
    postOrder() {
        const res = [];
        this.#dfs(0, 'post', res);
        return res;
    }
}
array_binary_tree.ts
/* 二分木を配列で表すクラス */
class ArrayBinaryTree {
    #tree: (number | null)[];

    /* コンストラクタ */
    constructor(arr: (number | null)[]) {
        this.#tree = arr;
    }

    /* リストの容量 */
    size(): number {
        return this.#tree.length;
    }

    /* インデックス i のノードの値を取得する */
    val(i: number): number | null {
        // 範囲外なら空きを示す null を返す
        if (i < 0 || i >= this.size()) return null;
        return this.#tree[i];
    }

    /* インデックス i のノードの左の子のインデックスを取得する */
    left(i: number): number {
        return 2 * i + 1;
    }

    /* インデックス i のノードの右の子のインデックスを取得する */
    right(i: number): number {
        return 2 * i + 2;
    }

    /* インデックス i のノードの親のインデックスを取得する */
    parent(i: number): number {
        return Math.floor((i - 1) / 2); // 商を負の無限大の方向に切り下げる
    }

    /* レベル順走査 */
    levelOrder(): number[] {
        let res = [];
        // 配列を順に走査する
        for (let i = 0; i < this.size(); i++) {
            if (this.val(i) !== null) res.push(this.val(i));
        }
        return res;
    }

    /* 深さ優先走査 */
    #dfs(i: number, order: Order, res: (number | null)[]): void {
        // 空きなら戻る
        if (this.val(i) === null) return;
        // 行きがけ順走査
        if (order === 'pre') res.push(this.val(i));
        this.#dfs(this.left(i), order, res);
        // 通りがけ順走査
        if (order === 'in') res.push(this.val(i));
        this.#dfs(this.right(i), order, res);
        // 帰りがけ順走査
        if (order === 'post') res.push(this.val(i));
    }

    /* 行きがけ順走査 */
    preOrder(): (number | null)[] {
        const res = [];
        this.#dfs(0, 'pre', res);
        return res;
    }

    /* 通りがけ順走査 */
    inOrder(): (number | null)[] {
        const res = [];
        this.#dfs(0, 'in', res);
        return res;
    }

    /* 帰りがけ順走査 */
    postOrder(): (number | null)[] {
        const res = [];
        this.#dfs(0, 'post', res);
        return res;
    }
}
array_binary_tree.dart
/* 二分木を配列で表すクラス */
class ArrayBinaryTree {
  late List<int?> _tree;

  /* コンストラクタ */
  ArrayBinaryTree(this._tree);

  /* リストの容量 */
  int size() {
    return _tree.length;
  }

  /* インデックス i のノードの値を取得する */
  int? val(int i) {
    // 範囲外なら空きを示す null を返す
    if (i < 0 || i >= size()) {
      return null;
    }
    return _tree[i];
  }

  /* インデックス i のノードの左の子のインデックスを取得する */
  int? left(int i) {
    return 2 * i + 1;
  }

  /* インデックス i のノードの右の子のインデックスを取得する */
  int? right(int i) {
    return 2 * i + 2;
  }

  /* インデックス i のノードの親のインデックスを取得する */
  int? parent(int i) {
    return (i - 1) ~/ 2;
  }

  /* レベル順走査 */
  List<int> levelOrder() {
    List<int> res = [];
    for (int i = 0; i < size(); i++) {
      if (val(i) != null) {
        res.add(val(i)!);
      }
    }
    return res;
  }

  /* 深さ優先走査 */
  void dfs(int i, String order, List<int?> res) {
    // 空きなら戻る
    if (val(i) == null) {
      return;
    }
    // 行きがけ順走査
    if (order == 'pre') {
      res.add(val(i));
    }
    dfs(left(i)!, order, res);
    // 通りがけ順走査
    if (order == 'in') {
      res.add(val(i));
    }
    dfs(right(i)!, order, res);
    // 帰りがけ順走査
    if (order == 'post') {
      res.add(val(i));
    }
  }

  /* 行きがけ順走査 */
  List<int?> preOrder() {
    List<int?> res = [];
    dfs(0, 'pre', res);
    return res;
  }

  /* 通りがけ順走査 */
  List<int?> inOrder() {
    List<int?> res = [];
    dfs(0, 'in', res);
    return res;
  }

  /* 帰りがけ順走査 */
  List<int?> postOrder() {
    List<int?> res = [];
    dfs(0, 'post', res);
    return res;
  }
}
array_binary_tree.rs
/* 二分木を配列で表すクラス */
struct ArrayBinaryTree {
    tree: Vec<Option<i32>>,
}

impl ArrayBinaryTree {
    /* コンストラクタ */
    fn new(arr: Vec<Option<i32>>) -> Self {
        Self { tree: arr }
    }

    /* リストの容量 */
    fn size(&self) -> i32 {
        self.tree.len() as i32
    }

    /* インデックス i のノードの値を取得する */
    fn val(&self, i: i32) -> Option<i32> {
        // 範囲外なら空きを示す None を返す
        if i < 0 || i >= self.size() {
            None
        } else {
            self.tree[i as usize]
        }
    }

    /* インデックス i のノードの左の子のインデックスを取得する */
    fn left(&self, i: i32) -> i32 {
        2 * i + 1
    }

    /* インデックス i のノードの右の子のインデックスを取得する */
    fn right(&self, i: i32) -> i32 {
        2 * i + 2
    }

    /* インデックス i のノードの親のインデックスを取得する */
    fn parent(&self, i: i32) -> i32 {
        (i - 1) / 2
    }

    /* レベル順走査 */
    fn level_order(&self) -> Vec<i32> {
        self.tree.iter().filter_map(|&x| x).collect()
    }

    /* 深さ優先走査 */
    fn dfs(&self, i: i32, order: &'static str, res: &mut Vec<i32>) {
        if self.val(i).is_none() {
            return;
        }
        let val = self.val(i).unwrap();
        // 行きがけ順走査
        if order == "pre" {
            res.push(val);
        }
        self.dfs(self.left(i), order, res);
        // 通りがけ順走査
        if order == "in" {
            res.push(val);
        }
        self.dfs(self.right(i), order, res);
        // 帰りがけ順走査
        if order == "post" {
            res.push(val);
        }
    }

    /* 行きがけ順走査 */
    fn pre_order(&self) -> Vec<i32> {
        let mut res = vec![];
        self.dfs(0, "pre", &mut res);
        res
    }

    /* 通りがけ順走査 */
    fn in_order(&self) -> Vec<i32> {
        let mut res = vec![];
        self.dfs(0, "in", &mut res);
        res
    }

    /* 帰りがけ順走査 */
    fn post_order(&self) -> Vec<i32> {
        let mut res = vec![];
        self.dfs(0, "post", &mut res);
        res
    }
}
array_binary_tree.c
/* 二分木を配列で表す構造体 */
typedef struct {
    int *tree;
    int size;
} ArrayBinaryTree;

/* コンストラクタ */
ArrayBinaryTree *newArrayBinaryTree(int *arr, int arrSize) {
    ArrayBinaryTree *abt = (ArrayBinaryTree *)malloc(sizeof(ArrayBinaryTree));
    abt->tree = malloc(sizeof(int) * arrSize);
    memcpy(abt->tree, arr, sizeof(int) * arrSize);
    abt->size = arrSize;
    return abt;
}

/* デストラクタ */
void delArrayBinaryTree(ArrayBinaryTree *abt) {
    free(abt->tree);
    free(abt);
}

/* リストの容量 */
int size(ArrayBinaryTree *abt) {
    return abt->size;
}

/* インデックス i のノードの値を取得する */
int val(ArrayBinaryTree *abt, int i) {
    // 範囲外なら空きを示す INT_MAX を返す
    if (i < 0 || i >= size(abt))
        return INT_MAX;
    return abt->tree[i];
}

/* レベル順走査 */
int *levelOrder(ArrayBinaryTree *abt, int *returnSize) {
    int *res = (int *)malloc(sizeof(int) * size(abt));
    int index = 0;
    // 配列を順に走査する
    for (int i = 0; i < size(abt); i++) {
        if (val(abt, i) != INT_MAX)
            res[index++] = val(abt, i);
    }
    *returnSize = index;
    return res;
}

/* 深さ優先走査 */
void dfs(ArrayBinaryTree *abt, int i, char *order, int *res, int *index) {
    // 空きなら戻る
    if (val(abt, i) == INT_MAX)
        return;
    // 行きがけ順走査
    if (strcmp(order, "pre") == 0)
        res[(*index)++] = val(abt, i);
    dfs(abt, left(i), order, res, index);
    // 通りがけ順走査
    if (strcmp(order, "in") == 0)
        res[(*index)++] = val(abt, i);
    dfs(abt, right(i), order, res, index);
    // 帰りがけ順走査
    if (strcmp(order, "post") == 0)
        res[(*index)++] = val(abt, i);
}

/* 行きがけ順走査 */
int *preOrder(ArrayBinaryTree *abt, int *returnSize) {
    int *res = (int *)malloc(sizeof(int) * size(abt));
    int index = 0;
    dfs(abt, 0, "pre", res, &index);
    *returnSize = index;
    return res;
}

/* 通りがけ順走査 */
int *inOrder(ArrayBinaryTree *abt, int *returnSize) {
    int *res = (int *)malloc(sizeof(int) * size(abt));
    int index = 0;
    dfs(abt, 0, "in", res, &index);
    *returnSize = index;
    return res;
}

/* 帰りがけ順走査 */
int *postOrder(ArrayBinaryTree *abt, int *returnSize) {
    int *res = (int *)malloc(sizeof(int) * size(abt));
    int index = 0;
    dfs(abt, 0, "post", res, &index);
    *returnSize = index;
    return res;
}
array_binary_tree.kt
/* 二分木を配列で表すクラス */
class ArrayBinaryTree(val tree: MutableList<Int?>) {
    /* リストの容量 */
    fun size(): Int {
        return tree.size
    }

    /* インデックス i のノードの値を取得する */
    fun _val(i: Int): Int? {
        // 範囲外なら空きを示す null を返す
        if (i < 0 || i >= size()) return null
        return tree[i]
    }

    /* インデックス i のノードの左の子のインデックスを取得する */
    fun left(i: Int): Int {
        return 2 * i + 1
    }

    /* インデックス i のノードの右の子のインデックスを取得する */
    fun right(i: Int): Int {
        return 2 * i + 2
    }

    /* インデックス i のノードの親のインデックスを取得する */
    fun parent(i: Int): Int {
        return (i - 1) / 2
    }

    /* レベル順走査 */
    fun levelOrder(): MutableList<Int?> {
        val res = mutableListOf<Int?>()
        // 配列を順に走査する
        for (i in 0..<size()) {
            if (_val(i) != null)
                res.add(_val(i))
        }
        return res
    }

    /* 深さ優先走査 */
    fun dfs(i: Int, order: String, res: MutableList<Int?>) {
        // 空きなら戻る
        if (_val(i) == null)
            return
        // 行きがけ順走査
        if ("pre" == order)
            res.add(_val(i))
        dfs(left(i), order, res)
        // 通りがけ順走査
        if ("in" == order)
            res.add(_val(i))
        dfs(right(i), order, res)
        // 帰りがけ順走査
        if ("post" == order)
            res.add(_val(i))
    }

    /* 行きがけ順走査 */
    fun preOrder(): MutableList<Int?> {
        val res = mutableListOf<Int?>()
        dfs(0, "pre", res)
        return res
    }

    /* 通りがけ順走査 */
    fun inOrder(): MutableList<Int?> {
        val res = mutableListOf<Int?>()
        dfs(0, "in", res)
        return res
    }

    /* 帰りがけ順走査 */
    fun postOrder(): MutableList<Int?> {
        val res = mutableListOf<Int?>()
        dfs(0, "post", res)
        return res
    }
}
array_binary_tree.rb
### 二分木を配列で表すクラス ###
class ArrayBinaryTree
  ### コンストラクタ ###
  def initialize(arr)
    @tree = arr.to_a
  end

  ### リストの容量 ###
  def size
    @tree.length
  end

  ### インデックス i のノードの値を取得する ###
  def val(i)
    # 範囲外なら空きを示す nil を返す
    return if i < 0 || i >= size

    @tree[i]
  end

  ### インデックス i のノードの左の子のインデックスを取得する ###
  def left(i)
    2 * i + 1
  end

  ### インデックス i のノードの右の子のインデックスを取得する ###
  def right(i)
    2 * i + 2
  end

  ### インデックス i のノードの親のインデックスを取得する ###
  def parent(i)
    (i - 1) / 2
  end

  ### レベル順走査 ###
  def level_order
    @res = []

    # 配列を順に走査する
    for i in 0...size
      @res << val(i) unless val(i).nil?
    end

    @res
  end

  ### 深さ優先走査 ###
  def dfs(i, order)
    return if val(i).nil?
    # 行きがけ順走査
    @res << val(i) if order == :pre
    dfs(left(i), order)
    # 通りがけ順走査
    @res << val(i) if order == :in
    dfs(right(i), order)
    # 帰りがけ順走査
    @res << val(i) if order == :post
  end

  ### 行きがけ順走査 ###
  def pre_order
    @res = []
    dfs(0, :pre)
    @res
  end

  ### 通りがけ順走査 ###
  def in_order
    @res = []
    dfs(0, :in)
    @res
  end

  ### 帰りがけ順走査 ###
  def post_order
    @res = []
    dfs(0, :post)
    @res
  end
end
実行の様子を見る

7.3.3   利点と制約

二分木の配列表現には、主に次の利点があります。

  • 配列は連続したメモリ領域に格納されるのでキャッシュを活用しやすく、アクセスや走査が高速です。
  • ポインタを格納する必要がなく、メモリを節約できます。
  • ノードにランダムアクセスできます。

一方、配列表現には次のような制約もあります。

  • 配列には連続したメモリ領域が必要なため、データ量が非常に大きい木の格納には適しません。
  • ノードの追加や削除には配列への挿入や配列からの削除が必要で、効率がよくありません。
  • 二分木に None が多いと、配列のうち実際のノードのデータが占める割合が小さくなり、メモリの利用効率が下がります。
ご意見、ご質問、ご提案をコメント欄にお寄せください。