您的位置:首页 > 编程语言 > C#

关于C#集合想法与疑问(二)---自定义集合 C#二叉树实现

2013-05-22 20:15 399 查看
对于C#中,自定义集合,其中最重要的就是构建迭代器,不同的迭代器可以有不同的访问遍历顺序,,以下是自定义集合里二叉树的实现,仅作为例子,但是在构建中序遍历的迭代器时出现了点问题,,可能虽然了解yield return 不过是编译器给的语法糖,而实质是变异器自动产生枚举数类并根据yield return 实现IEnumerator接口,但是可能终究是理解不够,在构建中序遍历的迭代器时出现了问题,望各位大神指正: 具体细节,请看代码::
using System.IO;
using System;
using System.Collections.Generic;
using CollectionsFuther;
class Program
{
static void Main()
{
var family=new BinaryTree<string>("grandfather");
family.LeftTree=new BinaryTree<string>("Father")
{
Value="Father",
LeftTree=new BinaryTree<string>("brother"),
RightTree=new BinaryTree<string>("I")
};
family.RightTree=new BinaryTree<string>("uncle")
{
Value="uncle",
LeftTree=new BinaryTree<string>("Cousin")
//RightTree=new BinaryTree<string>("I")
};

Console.WriteLine("Traversing in the order of DLR (node->Left->right");
foreach(var member in family)
{
Console.WriteLine(member);
}

Console.WriteLine("Traversing in the order of DLR (left->node->right");
foreach (var member in family.MidGetEnumerator())
{
Console.WriteLine(member);
}
Console.ReadKey();

}

}
 

二叉树代码:

using System.Collections.Generic;
using System;

namespace CollectionsFuther
{
public class BinaryTree<T> :IEnumerable<T>
{
#region Properites
public T Value { get; set;}
public BinaryTree<T> LeftTree {get;set;}
public BinaryTree<T> RightTree {get;set;}
#endregion

#region Constructor
public BinaryTree (T value)
{
this.Value=value;
}
#endregion

#region Method
public bool Insert(BinaryTree<T> tree)
{
return true;
}
public bool Delete(BinaryTree<T> tree)
{
return true;
}

#region IEnumerable
//Traversing in the order of node->Left->Right
public IEnumerator<T>  GetEnumerator()
{

yield return Value;
if(LeftTree==null)
{
yield break;
}
else
{
foreach(var item in LeftTree)
{
yield return item;
}
}

if(RightTree==null)
{
yield break;
}
else
{
foreach(var item in RightTree)
{
yield return item;
}
}

}

//Traversing in the order of Left->Node->Right
public IEnumerable<T> MidGetEnumerator()
{
if(LeftTree!=null)
{
foreach(var item in LeftTree)
{
yield return item;
}
}
yield return Value;
if(RightTree!=null)
{
foreach(var item in RightTree)
{
yield return item;
}
}

}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion

#endregion

}
}

输出 output:

Traversing in the order of DLR (node->Left->right

grandfather

father

brother

I

uncle

cousin

Traversing in the order of DLR (left->node->right

Father

brother

I

grandfather

uncle

cousin

对于中序遍历的结果是错误的,,,求解中,,,,
 
 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# 集合