1: binary tree node22
932

使


用語

編集

 edge leaf (external node)  (internal node) (depth) root  path-1(level)  (height)  (siblings) pqpq(ancestor)qp(descendant) (size) 

種類

編集

2 (full binary tree)  (perfect binary tree, complete binary tree) 

Complete binary treenn n-1 

(almost complete binary tree) 

グラフ理論での定義

編集

 (connected)  (acyclic)  (vertex)  (degree) 3 13222

2 (forest) 

:



 a, b vva, b


データの二分木への格納法

編集
 
Pascalコードで定義されたデータ型の利用イメージ

 nilnull Pascal

type
  pNode = ^Node; {ノード型へのポインタ}
  Node = record
    data : (* 必要なデータをためる部分 *)
    left, parent, right : pNode
    {左の子、親、右の子へのポインタ}
  end;
...
var root, newnode : pNode;
...
begin
  new(root); root^.parent := nil;
  {根を植える。根には親がいない}
  new(newnode); {新しいノードをつくる}
  with newnode^ do begin
    left := nil; right := nil; {子はいない}
    parent := root {rootが親}
  end;
  root^.left := newnode; {左側の子に}
  new(newnode); {新しいノードをつくる}
  with newnode^ do begin
    left := nil; right := nil; {子はいない}
    parent := root {rootが親}
  end;
  root^.right := newnode {右側の子に}
...

0 i2i + 1 2i + 2  floor((i-1)/2) preorder traversal n h2h - n
配列に格納された小規模な完全二分木 

ML3-tuplePascalC nil 

二分木を巡回する方法

編集

しばしば、ある二分木に属する各々のノードを調べる必要が出てくる。ノードを訪れる順番には定番的なものがあり、それぞれ利点がある。

行きがけ順、通りがけ順、帰りがけ順探索

編集

二分木においてはあるノードとその子孫もまた二分木を構成する。これを部分木と呼ぶ。 従って二分木を部分木に分け、再帰を用いて探索する方法は自然である。根を調べてからそれにぶらさがる部分木を調べるのが行きがけ順 (preorder)、部分木を調べてからその根を調べるのが帰りがけ順 (postorder) 、片方の部分木を調べ、根を調べ、次いで反対の部分木を調べるのが通りがけ順 (in-order) である。二分探索木では通りがけ順探索はノードを大きさ順(あるいは大きさの逆順)に調べることになる。

深さ優先探索

編集

調調

幅優先探索

編集

深さ優先探索と対照的に、未だに訪れていないノードを、根に近い方から探索する。

二分木の応用

編集
 
二分探索木(左上)、平衡木(下)、ヒープ(右上)

二分探索木

編集

 (binary search tree) 

x

n
x = n  

x > n  調

x < n  調


平衡二分探索木

編集


バイナリヒープ

編集

      

算術式の構文木

編集
 
算術式の二分木表現



a b + c d - × e f + ÷

(a + b) × (c - d) ÷ (e + f)

÷ × + a b - c d + e f

調

二分木構造のエンコーディング法

編集

簡潔符号化

編集

       bit  2bit 

10Pascaldata[1] :
function EncodeSuccinct(node n, bitstring structure, array data) {
    if (n = nil) then
        structure の最後に 0 を追加する
    else         
         structure の最後に1を追加する
        data の最後に n.data を追加する
        EncodeSuccinct(n.left, structure, data)
        EncodeSuccinct(n.right, structure, data)
}

string structure    bit    structurestring:
function DecodeSuccinct(bitstring structure, array data) {
    structure の最初のビットを取り除き、そのビットをbに入れる
   if ( b = 1 ) then
        新しいノードnを作る
        dataの最初の要素を取り除き、その要素を n.data に入れる
        n.left = DecodeSuccinct(structure, data)
        n.right = DecodeSuccinct(structure, data)
        n を返す
    else
        nil を返す
}

便

N進木の二分木表現

編集

 (ordered tree) LISPNnnNNnmNmNm



{B,C,D,E,F,G}6A
N進木の二分木表現 
N

LISP

(((M N) H I) C D ((O) (P)) F (L))


参考文献

編集
  • Donald Knuth. Fundamental Algorithms, Third Edition. Addison-Wesley, 1997. ISBN 0-201-89683-4. Section 2.3, especially subsections 2.3.1–2.3.2 (pp.318–348).

関連項目

編集