using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Node
{
public int Data;
public Node Left;
public Node Right;
public void DisplayNode()
{
Console.Write(Data + " ");
}
}
public class BinarySearchTree
{
public Node root;
public BinarySearchTree()
{
root = null;
}
public void Insert(int i)
{
Node newNode = new Node();
newNode.Data = i;
if (root == null)
root = newNode;
else
{
Node current = root;
Node parent;
while (true)
{
parent = current;
if (i < current.Data)
{
current = current.Left;
if (current == null)
{
parent.Left = newNode;
break;
}
else
{
current = current.Right;
if (current == null)
{
parent.Right = newNode;
break;
}
}
}
}
}
}
public void InOrder(Node theRoot)
{
if (!(theRoot == null))
{
InOrder(theRoot.Left);
theRoot.DisplayNode();
InOrder(theRoot.Right);
}
}
static void Main()
{
BinarySearchTree nums = new BinarySearchTree();
nums.Insert(23);
nums.Insert(45);
nums.Insert(16);
nums.Insert(37);
nums.Insert(3);
nums.Insert(99);
nums.Insert(22);
Console.WriteLine("Inorder traversal: ");
nums.InOrder(nums.root);
}
}
}
答案 0 :(得分:2)
你的插入函数中有一个无限循环;您正在处理i < current.data
的情况,但如果i >= current.data
则会陷入while(true)
。我认为您需要将current = current.right
代码移动到嵌套级别,即
while (true)
{
parent = current;
if (i < current.Data)
{
current = current.Left;
if (current == null)
{
parent.Left = newNode;
break;
}
}
else
{
current = current.Right;
if (current == null)
{
parent.Right = newNode;
break;
}
}
}
请注意,其他人现在if (i < current.Data) ... else
而不是if (current == null) ... else
。
但实际上你需要学习使用调试器来自己诊断这类事情。
答案 1 :(得分:0)
也许是
Console.Write(Data.ToString() + " ");