有很多方法可以做到这一点!看看Tree traversal 的想法。
从您的示例看来,您应该在每个节点上使用一些范围。
只是为了好玩,我尝试(非常快速地)构建一些代码 - 同样,这是在不知道您在搜索中使用哪些参数的情况下完成的。请注意,这只是一个示例,构建速度非常快:
节点结构
class Node
{
public int Min { get; set; }
public int Max { get; set; }
public List<Node> Children { get; set; }
public Node(int min, int max)
{
this.Min = min;
this.Max = max;
this.Children = new List<Node>();
}
public void Add(Node child)
{
this.Children.Add(child);
}
}
一个主类
该类包含一个用于构建树的函数(不漂亮),以及一个递归函数,并返回级别,并输出节点对象。
class Program
{
static void Main(string[] args)
{
var tree = GetTree();
Node node;
var val = Find(tree, 21, 1, out node);
Console.WriteLine("depth: {0}", val);
Console.WriteLine("\t{0}, {1}", node.Min, node.Max);
Console.ReadKey();
}
private static int Find(Node curNode, int value, int level, out Node foundNode)
{
foundNode = curNode;
foreach (var child in curNode.Children)
{
if (child.Min <= value && child.Max >= value)
return Find(child, value, level + 1, out foundNode);
}
return level;
}
private static Node GetTree()
{
var a = new Node(20, 40);
var b = new Node(21, 22);
var c = new Node(23, 33);
var d = new Node(24, 29);
var e = new Node(25, 26);
var f = new Node(27, 28);
var g = new Node(30, 31);
var h = new Node(32, 33);
var i = new Node(34, 37);
var j = new Node(35, 36);
var k = new Node(38, 39);
d.Add(e);
d.Add(f);
c.Add(d);
c.Add(g);
c.Add(h);
i.Add(j);
a.Add(b);
a.Add(c);
a.Add(i);
a.Add(k);
return a;
}
}
private static Node GetTree()
{
var a = new Node(20, 40);
var b = new Node(21, 22);
var c = new Node(23, 33);
var d = new Node(24, 29);
var e = new Node(25, 26);
var f = new Node(27, 28);
var g = new Node(30, 31);
var h = new Node(32, 33);
var i = new Node(34, 37);
var j = new Node(35, 36);
var k = new Node(38, 39);
d.Add(e);
d.Add(f);
c.Add(d);
c.Add(g);
c.Add(h);
i.Add(j);
a.Add(b);
a.Add(c);
a.Add(i);
a.Add(k);
return a;
}