1 / 7

二分木のメソッド(続き)

二分木のメソッド(続き). 中間順に木をなぞるメソッド. class Vertex def initialize … attr_attribute :data, :left, :right. def inorder # 中間順でなぞる @left.inorder if @left != nil # v の左の子をなぞる print @data # 頂点のラベルを表示 @right.inorder if @right != nil # v の右の子をなぞる

Download Presentation

二分木のメソッド(続き)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 二分木のメソッド(続き)

  2. 中間順に木をなぞるメソッド class Vertex def initialize … attr_attribute :data, :left, :right def inorder # 中間順でなぞる @left.inorder if @left != nil# vの左の子をなぞる print @data # 頂点のラベルを表示 @right.inorder if @right != nil# vの右の子をなぞる end # def of inorder end # class

  3. 先行順、後行順に木をなぞるメソッド class Vertex def initialize … attr_attribute :data, :left, :right def # 中間順でなぞる @left.inorder if @left != nil# vの左の子をなぞる print @data # 頂点のラベルを表示 @right.inorder if @right != nil# vの右の子をなぞる end # def preorder postorder inorder 後行 先行 @left.preorder if @left != nil# vの左の子をなぞる @left.postorder if @left != nil# vの左の子をなぞる print @data # 頂点のラベルを表示 @right.preorder if @right != nil# vの右の子をなぞる @right.postoder if @right != nil# vの右の子をなぞる end # class

  4. 「高さ」を返すメソッド この木の高さは? 左部分木の高さ と 右部分木の高さ    の大きい方+1 左部分木の高さ= @left.height 右部分木の高さ= @left.height ただし子がいない時も考慮すること (例えば両方とも子がいない=葉の場合は、高さ0!)

  5. 考えるべきケース • 子ノードがない場合:                                             これは高さ 0 • 左(または右)の子ノードだけがある場合 • 両方の子がある場合 子ノードを根とする 部分木の高さ+1 左子ノードを根とする部分木の高さ 右子ノードを根とする部分木の高さ   の大きいほう+1 (前のスライド参照)

  6. 「高さ」を返すメソッド(続) class Vertex def initialize … attr_attribute :data, :left, :right def height if (@left != nil) # 左の子あり leftHeight = @left.height elsif (@right != nil)# 左の子なし、右の子あり return1+@right.height else# 左の子も右の子もなし return 0 # 葉 end # if --- 左の子がある場合のみ残る if (@right != nil) # 右の子あり rightHeight = @right.height else # 右の子なし return1+leftHight end # if --- 二つの子あり if (leftHeight > rightHeight) return 1+leftHeight else return1+rightHeight end # if end # def end # class

  7. 葉を表示するメソッド class Vertex def initialize … attr_attribute :data, :left, :right def inorder # 中間順でなぞる @left.inorder if @left != nil# vの左の子をなぞる print @data # 頂点のラベルを表示 @right.inorder if @right != nil# vの右の子をなぞる end # def of inorder このままだと「葉」以外の頂点も表示 そこで「葉」の条件を加えれば良い end # class それは、子頂点がないこと! print @data if (@left == nil) && (@right == nil) 注意:showが返す「配列」から求めても良いが、Vertexクラスのメソッドにならない

More Related