BSTをいじくり回していて、私はそれらについてかなり良い考えを持っていますが、BST内の特定のノードを検索して、それが存在するかどうかを教えてもらいたいと思います。私はBSTで文字列を使用しており、すべてがうまく機能しているようですが、このFindメソッドを理解できません。誰かが私が間違っていることとそれを修正する方法を教えてくれるなら、これはありがたいです。
class Node
{
public string number;
public string data;
public Node left;
public Node right;
public string Content;
public Node(string data)
{
this.data = data;
}
}
class BinarySearchTree
{
public Node root, current;
public BinarySearchTree()
{
this.root = null;
}
public void AddNode(string a) // code to insert nodes to the binary search tree
{
Node newNode = new Node(a); //create a new node
if (root == null) // if the tree is empty new node will be the root node
root = newNode;
else
{
Node previous;
current = root;
while (current != null)
{
previous = current;
if (a.CompareTo(current.data) < 1) //if the new node is less than the current node
{
current = current.left;
if (current == null)
previous.left = newNode;
}
else //if the new node is greater than the current node
{
current = current.right;
if (current == null)
previous.right = newNode;
}
}
}
}
public string FindNode(Node node, string s)
{
if (root == null)
return Output = "not found";
else if (s.CompareTo(root.data) < 1)
return FindNode(root.left, s);
else if (s.CompareTo(root.data) > 1)
return FindNode(root.right, s);
return Output = "found";
}
string SearchResult = "";
static string Output = "";
public string Display(Node rootNode)
{
if (rootNode != null)
{
Display(rootNode.left);
Output += rootNode.data;
Display(rootNode.right);
}
return Output;
}
}
private void btnExecute_Click(object sender, EventArgs e)
{
BinarySearchTree btree = new BinarySearchTree();
btree.AddNode("D");
btree.AddNode("B");
btree.AddNode("F");
btree.AddNode("E");
btree.AddNode("A");
btree.AddNode("G");
btree.AddNode("C");
string target;
txtOutput.Text += "The sorted values of the Binary Search Tree are: \r\n \r\n";
txtOutput.Text += btree.Display(btree.root);
txtOutput.Text += btree.FindNode(btree.root, "A");
}
以下に変更してみます:
1.のCompareTo
0ではない1と方法を、そうa.CompareTo(current.data) < 1
でなければなりませんa.CompareTo(current.data) < 0
を参照してくださいドキュメントIComparable.CompareTo方法
あなたのように2FindNode
再帰呼び出しで、変更root
へのnode
使用方法
public string FindNode(Node node, string s)
{
if (node == null)
return Output = "not found";
else if (s.CompareTo(node.data) < 0)
return FindNode(node.left, s);
else if (s.CompareTo(node.data) > 0)
return FindNode(node.right, s);
return Output = "found";
}
がんばろう!
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加