假设我有这棵树:
O-ROOT
/ \
O-A O-B
/ / \
O-A1 O-B1 O-B2
我希望在C#中执行此操作:
1. Check every node starting from root (I think the best way is trought recursion?);
2. If I found a node with value = "Hello", return true and STOP the searching function;
你能帮助我做出最好的算法吗?
答案 0 :(得分:2)
我认为解决问题的最佳方法是使用breadth first search。写起来很简单,并且尽可能有效。
编辑:类似这样的事情:public bool Search(TreeNode node, string searchString)
{
Queue<Control> q = new Queue<Node>();
q.Enqueue(node);
while(!q.empty()) {
Node current = q.Dequeue();
foreach(var childNode in node.Children)
if(childNode.Content.CompareTo(searchString) == 0) {
return true;
}
q.Enqueue(childNode);
}
}
return false;
}
答案 1 :(得分:2)
bool FindHello(Node node)
{
if (node.Content == "Hello")
return true;
foreach (Node c in node.Children)
if (FindHello(c))
return true;
return false;
}
答案 2 :(得分:1)
Breadth First Search和Depth First Search是最受欢迎(以及其他)树搜索技术之一,因此您可以从那里开始。此外,如果树中的每个节点最多有2个节点,并且它们以某种方式排序,则可以使用Binary Search Tree技术。
答案 3 :(得分:1)
您对递归是正确的,请参阅depth-first或广度优先搜索算法。由于您没有已访问过的节点的保持列表,因此树更容易。
public bool Search(TreeNode node, string searchString)
{
if(node.Value == searchString) return true;
foreach(var childNode in node.Children)
if(Search(childNode, searchString)) return true;
return false;
}
答案 4 :(得分:0)