非二叉树查找叶节点(C#)
Non-binary tree finding leaf nodes (C#)
Child c1 = new Child();
c1.name = "c1";
c1.Isleaf = false;
Child c2 = new Child();
c2.name = "c2";
c2.Isleaf = true;
Child c11 = new Child();
c11.name = "c11";
c11.Isleaf = true;
Child c12 = new Child();
c12.name = "c12";
c12.Isleaf = false;
Child c121 = new Child();
c121.name = "c121";
c121.Isleaf = true;
c12.Children = new List<Child>() { c121 };
c1.Children = new List<Child>() { c11, c12 };
Parent p = new Parent();
p.name = "P1";
p.Children = new List<Child>() { c1, c2 };
List<Child> leaves = new List<Child>();
enter code here
我使用 Queue
如下实现查找叶子
static public void FindLeavesQueue(Parent p, List<Child> leaves)
{
if (p.Children == null) return;
var toVisit = new Queue<Child>(p.Children);
while (toVisit.Count > 0)
{
var current = toVisit.Dequeue();
if (current.Isleaf)
leaves.Add(current);
if (current.Children != null)
{
foreach (var child in current.Children)
{
if (child.Isleaf)
leaves.Add(child);
else
{
foreach (Child c in child.Children)
toVisit.Enqueue(c);
}
}
}
}
}
enter code here
但在我的应用程序中,这 运行 非常慢。因为树真的很大,涉及到数据库事务。
让它更快的最好方法是什么?
谢谢
递归下降简单且快速,无需将内容复制到队列。
static public void FindLeaves(Parent p, List<Child> leaves)
{
if (p.Children == null) return;
foreach(var child in p.Children)
{
if(child.IsLeaf)
leaves.Add(child);
else
FindLeaves(child, leaves);
}
}
Child c1 = new Child();
c1.name = "c1";
c1.Isleaf = false;
Child c2 = new Child();
c2.name = "c2";
c2.Isleaf = true;
Child c11 = new Child();
c11.name = "c11";
c11.Isleaf = true;
Child c12 = new Child();
c12.name = "c12";
c12.Isleaf = false;
Child c121 = new Child();
c121.name = "c121";
c121.Isleaf = true;
c12.Children = new List<Child>() { c121 };
c1.Children = new List<Child>() { c11, c12 };
Parent p = new Parent();
p.name = "P1";
p.Children = new List<Child>() { c1, c2 };
List<Child> leaves = new List<Child>();
enter code here
我使用 Queue
如下实现查找叶子static public void FindLeavesQueue(Parent p, List<Child> leaves)
{
if (p.Children == null) return;
var toVisit = new Queue<Child>(p.Children);
while (toVisit.Count > 0)
{
var current = toVisit.Dequeue();
if (current.Isleaf)
leaves.Add(current);
if (current.Children != null)
{
foreach (var child in current.Children)
{
if (child.Isleaf)
leaves.Add(child);
else
{
foreach (Child c in child.Children)
toVisit.Enqueue(c);
}
}
}
}
}
enter code here
但在我的应用程序中,这 运行 非常慢。因为树真的很大,涉及到数据库事务。 让它更快的最好方法是什么? 谢谢
递归下降简单且快速,无需将内容复制到队列。
static public void FindLeaves(Parent p, List<Child> leaves)
{
if (p.Children == null) return;
foreach(var child in p.Children)
{
if(child.IsLeaf)
leaves.Add(child);
else
FindLeaves(child, leaves);
}
}