Reputation: 934
I am trying to search a BST for all of the nodes that contain a specific value, however when I call the search function it only returns the first match ( My test data def. has two nodes that should be returned). How do I adjust my code to get all of the values that match my criteria?
Here is my BST Search Function:
...
private String search(String target, Node ptr)
{
ptr = root;
if (ptr == null)
{
return null;
}
int compare = target.CompareTo(ptr.riskLevel.ToString());
if (compare == 0)
{
return "Audit ID: " + ptr.auditID +
"\n" + "Risk Level: " + ptr.riskLevel +
"\n" + "Scanner Found In: " + ptr.scanner +
"\n" + "Device Affected: " + ptr.boxName +
"\n" + "Description: " + ptr.description + "\n";
}
if (compare < 0)
{
return search(target, ptr.left);
}
return search(target, ptr.right);
}
public virtual String search(String target)
{
return search(target, root);
}
This is my main(); where I call the search method:
while (true)
{
...
Console.Writeline(bst.search("I"));
}
In other words, I'm trying to return all Nodes
from bst
that have a riskLevel
of "I"
.
Here is my output (there should be two):
My BST
contains the following methods:
I'm happy to post the entire BST
class if needed.
Upvotes: 0
Views: 275
Reputation: 934
I was not traversing the tree properly.
I reused this preOrder method from a previous project and it seems to be working like I would expect.
public List<String> filterRiskLevel(String target, List<string> results)
{
filterRiskLevel(target, root, results);
return results;
}
private void search(String target, Node ptr, List<string> results)
{
if (ptr != null)
{
if (ptr.riskLevel.Equals(target))
results.Add("Audit ID: " + ptr.auditID +
"\n" + "Risk Level: " + ptr.riskLevel +
"\n" + "Scanner Found In: " + ptr.scanner +
"\n" + "Device Affected: " + ptr.boxName +
"\n" + "Description: " + ptr.description + "\n");
filterRiskLevel(target, ptr.left, results);
filterRiskLevel(target, ptr.right, results);
}
}
Upvotes: 0
Reputation: 3702
I'm assuming that extra results are located in the 'right' subtree of previous results.
You had some problems with your code:
you replace the ptr node with root in the beginning?!
private void Search(String target, Node ptr, List<string> results)
{
if (ptr == null)
{
return;
}
int compare = target.CompareTo(ptr.riskLevel.ToString());
if (compare == 0)
{
string result = "Audit ID: " + ptr.auditID +
"\n" + "Risk Level: " + ptr.riskLevel +
"\n" + "Scanner Found In: " + ptr.scanner +
"\n" + "Device Affected: " + ptr.boxName +
"\n" + "Description: " + ptr.description + "\n";
results.Add(result);
search(target, ptr.right, results);
}
else if (compare < 0)
{
search(target, ptr.left, results);
}
else
{
search(target, ptr.right, results);
}
}
public virtual List<string> search(String target)
{
var results = new List<string>();
search(target, root, results);
return results;
}
Upvotes: 2