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);
开发者_JS百科 nums.Insert(99);
nums.Insert(22);
Console.WriteLine("Inorder traversal: ");
nums.InOrder(nums.root);
}
}
}
You've got an infinite loop in your Insert function; you're handling the case where i < current.data
but if i >= current.data
then it gets stuck in the while(true)
. I think you need to move the current = current.right
code up a nesting level, i.e.
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;
}
}
}
Note the else is now if (i < current.Data) ... else
not if (current == null) ... else
.
But really you need to learn to use the debugger to diagnose this sort of thing yourself.
Maybe it's
Console.Write(Data.ToString() + " ");
精彩评论