110,534
社区成员
发帖
与我相关
我的任务
分享
/// <summary>遍历查找节点
///
/// </summary>
/// <param name="tnParent">一级节点</param>
/// <param name="strValue">查找关键字</param>
/// <returns>返回找到的第一个节点</returns>
private TreeNode FindNode(TreeNode tnParent, string strValue)
{
if (tnParent == null)
return null;
if (tnParent.Text == strValue)
return tnParent;
TreeNode resultNode = null;
foreach (TreeNode node in tnParent.Nodes)
{
resultNode = FindNode(node, strValue);
if (resultNode != null)
break; //如果要继续查找,这里调整下
}
return resultNode;
}
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var xx = new A { Value = "1" };
xx.Children.Add(new A { Value = "2" });
xx.Children.Add(new A { Value = "3" });
xx.Children[0].Children.Add(new A { Value = "4" });
xx.Children[0].Children.Add(new A { Value = "5" });
xx.Children[1].Children.Add(new A { Value = "6" });
xx.Children[1].Children.Add(new A { Value = "7" });
foreach (var x in 深度优先搜索(xx))
Console.Write("{0} ", x.Value);
Console.WriteLine();
foreach (var x in 宽度优先搜索(xx))
Console.Write("{0} ", x.Value);
Console.WriteLine();
Console.WriteLine("................按任意键结束");
Console.ReadKey();
}
static private IEnumerable<A> 宽度优先搜索(A xx)
{
return 宽度优先搜索(new List<A> { xx });
}
static private IEnumerable<A> 宽度优先搜索(List<A> list)
{
if (list.Count > 0)
{
var 下一层 = new List<A>();
foreach (var x in list)
{
yield return x;
下一层.AddRange(x.Children);
}
foreach (var x in 宽度优先搜索(下一层))
yield return x;
}
}
static private IEnumerable<A> 深度优先搜索(A xx)
{
yield return xx;
foreach (var x in xx.Children)
foreach (var y in 深度优先搜索(x))
yield return y;
}
}
public class A
{
public string Value;
public List<A> Children = new List<A>();
}
}
你可以看到,宽度优先搜索,要重载函数,将参数改为“集合”方式,以便一层层地访问节点。using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var xx = new A { Value = "1" };
xx.Left = new A { Value = "2" };
xx.Right = new A { Value = "3" };
xx.Left.Left = new A { Value = "4" };
xx.Left.Right = new A { Value = "5" };
xx.Right.Left = new A { Value = "6" };
xx.Right.Right = new A { Value = "7" };
foreach (var x in 深度优先搜索(xx))
Console.Write("{0} ", x.Value);
Console.WriteLine();
foreach (var x in 宽度优先搜索(xx))
Console.Write("{0} ", x.Value);
Console.WriteLine();
Console.WriteLine("................按任意键结束");
Console.ReadKey();
}
static private IEnumerable<A> 宽度优先搜索(A xx)
{
return 宽度优先搜索(new List<A> { xx });
}
static private IEnumerable<A> 宽度优先搜索(List<A> list)
{
if (list.Count > 0)
{
var 下一层 = new List<A>();
foreach (var x in list)
if (x != null)
{
yield return x;
下一层.Add(x.Left);
下一层.Add(x.Right);
}
foreach (var x in 宽度优先搜索(下一层))
yield return x;
}
}
static private IEnumerable<A> 深度优先搜索(A xx)
{
yield return xx;
if (xx.Left != null)
foreach (var x in 深度优先搜索(xx.Left))
yield return x;
if (xx.Right != null)
foreach (var x in 深度优先搜索(xx.Right))
yield return x;
}
}
public class A
{
public string Value;
public A Left;
public A Right;
}
}