class Node
{
public int data;
public Node left, right;
public Node(int data)
{
this.data = data;
left = null;
right = null;
}
}
class BinaryTreeImp
{
Node root;
static int count = 0;
public BinaryTreeImp()
{
root = null;
}
public Node addNode(int data)
{
Node newNode = new Node(data);
if (root == null)
{
root = newNode;
}
count++;
return newNode;
}
public void insertNode(Node root,Node newNode)
{
Node temp;
temp = root;
if (newNode.data < temp.data)
{
if (temp.left == null)
{
temp.left = newNode;
}
else
{
temp = temp.left;
insertNode(temp,newNode);
}
}
else if (newNode.data > temp.data)
{
if (temp.right == null)
{
temp.right = newNode;
}
else
{
temp = temp.right;
insertNode(temp,newNode);
}
}
}
public void displayTree(Node root)
{
Node temp;
temp = root;
if (temp == null)
return;
displayTree(temp.left);
System.Console.Write(temp.data + " ");
displayTree(temp.right);
}
static void Main(string[] args)
{
BinaryTreeImp btObj = new BinaryTreeImp();
Node iniRoot= btObj.addNode(5);
btObj.insertNode(btObj.root,iniRoot);
btObj.insertNode(btObj.root,btObj.addNode(6));
btObj.insertNode(btObj.root,btObj.addNode(10));
btObj.insertNode(btObj.root,btObj.addNode(2));
btObj.insertNode(btObj.root,btObj.addNode(3));
btObj.displayTree(btObj.root);
System.Console.WriteLine("The sum of nodes are " + count);
Console.ReadLine();
}
}
Đây là mã cho mã implementation.The hoạt động tốt nhưng nếu trong hàm displayTree, tôi thay thế nó vớiBinary Search Tree trong C# Thực hiện
public void displayTree(Node root)
{
Node temp;
temp = root;
while(temp!=null)
{
displayTree(temp.left);
System.Console.Write(temp.data + " ");
displayTree(temp.right);
}
}
một vòng lặp vô hạn là do. Tôi không hiểu những gì đang gây ra điều này. Ngoài ra tôi muốn biết nếu có một cách tốt hơn để thực hiện một BST trong C#.
Bỏ phiếu để đóng: Yêu cầu người lạ phát hiện lỗi trong mã của bạn bằng cách kiểm tra không hiệu quả. Bạn nên xác định (hoặc ít nhất là cô lập) vấn đề bằng cách sử dụng trình gỡ rối hoặc báo cáo in và sau đó quay lại với câu hỏi cụ thể hơn (khi bạn đã thu hẹp câu hỏi xuống 10 dòng [test-case] (http://sscce.org)). –