需 求:无限级树查找功能,根据树节点名称查询的功能,支持反向查询(反向查询为从最后一个子节点开始查找)。
主要实现功能:可以对树实现正向(从上到下,从根到叶)、反向(从下到上,从叶到根)查询某节点。
实 现 思 路:正向查找:在递归子节之前先判断节点是否符合查找条件,不符合,进行递归子节;反向查找:先判断是否有子节,如果有递归子节,如若无,判断节点是否符合查找条件。
代 码:
class Program
{
static void Main(string[] args)
{
List<Node> nodes = new List<Node>()
{
new Node { ID = 1, Name = "1" },
new Node { ID = 2, Name = "2", ParentID = 1 },
new Node { ID = 3, Name = "3", ParentID = 1 },
new Node { ID = 4, Name = "4", ParentID = 1 },
new Node { ID = 5, Name = "5", ParentID = 2 },
new Node { ID = 6, Name = "6", ParentID = 2 },
new Node { ID = 7, Name = "7", ParentID = 2 },
new Node { ID = 8, Name = "8", ParentID = 7 },
new Node { ID = 9, Name = "9", ParentID = 7 },
new Node { ID = 10, Name = "10", ParentID = 7 }
};
// 绑定树
List<Node> outputList = Bind(nodes);
//从上向下查找树节点
Node node1 = FindDownward(outputList, 7);
//从下向上查找树节点
Node node2 = FindUpward(outputList, 7);
//从上向下查找树节点
Node node3 = FindDownward(outputList[0], 7);
//从下向上查找树节点
Node node4 = FindUpward(outputList[0], 7);
}
/// <summary>
/// 绑定树
/// </summary>
static List<Node> Bind(List<Node> nodes)
{
List<Node> outputList = new List<Node>();
for (int i = 0; i < nodes.Count; i++)
{
if (nodes.ParentID == -1) outputList.Add(nodes);
else FindDownward(nodes, nodes.ParentID).Nodes.Add(nodes);
}
return outputList;
}
/// <summary>
/// 向下查找
/// </summary>
static Node FindDownward(List<Node> nodes, int id)
{
if (nodes == null) return null;
for (int i = 0; i < nodes.Count; i++)
{
if (nodes.ID == id)
return nodes;
Node node = FindDownward(nodes.Nodes, id);
if (node != null) return node;
}
return null;
}
/// <summary>
/// 向下查找
/// </summary>
static Node FindDownward(Node node, int id)
{
if (node == null) return null;
if (node.ID == id) return node;
for (int i = 0; i < node.Nodes.Count; i++)
{
Node tempNode = FindDownward(node.Nodes, id);
if (tempNode != null) return tempNode;
}
return null;
}
/// <summary>
/// 向上查找
/// </summary>
static Node FindUpward(List<Node> nodes, int id)
{
if (nodes != null)
{
for (int i = nodes.Count - 1; i >= 0; i--)
{
Node node = FindUpward(nodes.Nodes, id);
if (node == null)
{
if (nodes.ID == id)
return nodes;
}
if (node != null)
return node;
}
}
return null;
}
/// <summary>
/// 向上查找
/// </summary>
static Node FindUpward(Node node, int id)
{
if (node == null) return null;
for (int i = node.Nodes.Count - 1; i >= 0; i--)
{
Node tempNode = FindUpward(node.Nodes, id);
if (tempNode != null)
return tempNode;
}
if (node.ID == id) return node;
return null;
}
}
/// <summary>
/// 实体类
/// </summary>
class Node
{
public Node()
{
this.Nodes = new List<Node>();
this.ParentID = -1;
}
public int ID { get; set; }
public string Name { get; set; }
public int ParentID { get; set; }
public List<Node> Nodes { get; set; }
} |