我有一个c#class
public class treeItem
{
public string parentName { get; set; }
public int index { get; set; }
public List<treeItem> children { get; set; }
public treeItem()
{
children = new List<treeItem>();
}
}
我可以填写它并按索引对其进行排序,但我在搜索3或n级索引时遇到问题 函数添加索引
void AddIndexToTree(List<treeItem> children)
{
for(int i = 0; i < children.Count; i++)
{
count++;
children[i].index = count;
if (children[i].children.Count > 0)
{
AddIndexToTree(children[i].children);
}
}
}
我尝试创建一个搜索功能,但在n级有一个问题,我从列表中删除项目,所以我发送一个列表的功能,但在n级别从原始列表中删除
treeItem getParentNode(int index, List<treeItem> searchList)
{
if (searchList.Count == 1)
{
if (searchList[0].index == index)
{
return searchList[0];
}
else if (searchList[0].children.Count > 0)
{
for (int i = 0; i < searchList[0].children.Count; i++ )
{
if (searchList[0].children[i].index == index)
return searchList[0].children[i];
}
List<treeItem> tempList = searchList[0].children;
return getParentNode(index, tempList);
}
}
else
{
int length = searchList.Count;
int mid;
if( length % 2 == 0)
{
mid = length / 2;
if (length != 2)
mid--;
}
else
{
mid = length / 2;
}
if (searchList[mid].index == index)
return searchList[mid];
if(searchList[mid].index > index)
{
searchList.RemoveRange(mid, searchList.Count - mid );
return getParentNode(index, searchList);
}
else
{
if (searchList.Count > 2 && searchList[mid + 1].index < index )
searchList.RemoveRange(0, mid + 1);
else
searchList.RemoveRange(0, mid);
return getParentNode(index, searchList);
}
}
return null;
}
我的代码或其他算法中的任何帮助都可以吗?
答案 0 :(得分:0)
这是一个简单的递归搜索树的特定索引的例子:(当然,这应该是你班级的方法)
public treeItem Find(int index)
{
if(this.Index == index)
return this;
foreach(var child in this.children)
return child.Find(index);
return null; // Index was not found in the current treeItem or any of it's children.
}
请注意,如果您的children属性中的treeItems按索引排序,则可以使用二进制搜索(我认为您尝试这样做)。