在日常开发中,经常遇到对树的操作,我们可以利用泛型和委托对这些树进行操作,这样就不需要每有一个树就要实现相应的功能了。
源码在https://files.cnblogs.com/haiconc/LangTest.zip
首先,使用类泛型声明:
public class TreeOperator<T,K>
在类内声明三个委托
public delegate K GetTreeKey(T tree);//取得树的Key
GetTreeKey GTK;
public delegate K GetParentKey(T tree);//取得树的父节点
GetParentKey GPK;
public delegate bool IsKeyEqual(K keyA, K keyB);//比较Key是否相等
IsKeyEqual IKE;
数据源:
List<T> source;
构造函数:
public int MaxDeep = 100;//防止在递归过程中进入无限死循环
public TreeOperator(GetTreeKey gti, GetParentKey gtp, IsKeyEqual ike , List<T> source, int deep)
{
this.GTK = gti;
this.GPK = gtp;
this.IKE = ike;
this.source = source;
this.MaxDeep = deep;
}
实现第一个功能
/// <summary>
/// 取得从根树到某个树的路径
/// </summary>
/// <param name="tree">某个树</param>
/// <param name="RootTree">根树</param>
/// <returns></returns>
public List<T> GetTreePath(T tree, T RootTree)
{
List<T> list = new List<T>();
T temp = tree;
int i = 0;
while (!IKE(GTK(temp), GTK(RootTree)))
{
list.Add(temp);
temp = GetParentTreeByTree(temp);
/* 防止进入死循环 */
i++;
while (i > MaxDeep)
{
break;
}
}
list.Add(RootTree);
list.Reverse();
return list;
}
private T GetTreeByKey(K key)
{
foreach (T tee in source)
{
if(IKE(GTK(tee),key))
return tee;
}
return default(T);
}
private T GetParentTreeByTree(T tree)
{
K key = GPK(tree);
return GetTreeByKey(key);
}
第二个功能实现:
/// <summary>
/// 取得某个树的所有子孙树
/// </summary>
/// <param name="tree"></param>
/// <param name="source"></param>
/// <returns></returns>
public List<T> GetAllSubTree(T tree)
{
List<T> list = new List<T>();
int deep = 0;
foreach (T tee in source)
{
if(IKE(GPK(tee),GTK(tree)))
{
list.Add(tee);
AddSub(tee, source, list, deep + 1);
}
}
return list;
}
private void AddSub(T tree, List<T> source,List<T> list ,int deep )
{
if (deep > MaxDeep) return;
foreach (T tee in source)
{
if (IKE(GPK(tee), GTK(tree)))
{
list.Add(tee);
AddSub(tee, source, list, deep + 1);
}
}
}
程序匆忙写成,有待改进。
源码在https://files.cnblogs.com/haiconc/LangTest.zip