明輝手游網(wǎng)中心:是一個(gè)免費(fèi)提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺(tái)!

數(shù)據(jù)結(jié)構(gòu)與算法(C#完成)---二叉樹

[摘要]using System;using System.Collections;namespace DataStructure /// <summary> /// BinaryTree 的摘要說(shuō)明。 /// </summary> public class...

 using System;
using System.Collections;namespace DataStructure
{
    /// <summary>
    /// BinaryTree 的摘要說(shuō)明。
    /// </summary>
    public class BinaryTree:NaryTree
    {
         //構(gòu)造二叉空樹
         public BinaryTree():base(2)
         {
             //
             // TODO: 在此處添加構(gòu)造函數(shù)邏輯
             //
         }
        
  public BinaryTree(object _obj):base(2,_obj)
         {
 
  }         //------------------------------------------------------
         protected override object GetEmptyInstance(uint _degree)
         {
      return new BinaryTree(_degree);
  }
         //------------------------------------------------------
 
         //重寫深度遍歷
         public override void DepthFirstTraversal(IPrePostVisitor _vis)
         {
              if ( !IsEmpty() )
              {
                  _vis.PreVisit(this.Key);
                  this[0].DepthFirstTraversal(_vis);
                  _vis.Visit(this.Key);
                  this[1].DepthFirstTraversal(_vis);
                  _vis.PostVisit(this.Key);
              }
          }
          //二叉樹大小的比較
          //先比較關(guān)鍵字,如果相等,再比較左子樹,如果再相等,則比較右子樹----如此遞歸
          #region IComparable 成員          public override int CompareTo(object obj)
          {
               // TODO: 添加 BinaryTree.CompareTo 實(shí)現(xiàn)
               //因?yàn)镃omare()中已經(jīng)進(jìn)行了類型斷定,故不會(huì)出現(xiàn)轉(zhuǎn)型錯(cuò)誤
               BinaryTree tmpTree=(BinaryTree)obj;
 
               if( this.IsEmpty() )
                   return tmpTree.IsEmpty()?0:-1;
               if( tmpTree.IsEmpty() )
                   return 1;
               int result=Comparer.Default.Compare(this,tmpTree);
               if(result==0)
                   result=this[0].CompareTo(tmpTree[0]);
               if(result==0)
                   result=this[1].CompareTo(tmpTree[1]);
 
               return result;
           }           #endregion
      }
 }