运行此代码时出现异常。
public void insertRBT(int value)
{
//BNode newNode = new BNode(value);
root=insertNode(root, value,null);
count += 1;
}
protected BNode insertNode(BNode rt, int value, BNode parent)
{
BNode grandParent, greatGrandParent;
if (rt == null)
{
BNode newNode = new BNode(value, parent);
parent = newNode.parent;
if (parent != null)
{
if (value > parent.value)
{
parent.right = newNode;
}
else {
parent.left = newNode;
}
}
if (count > 0)
{
newNode.red = true;
}
else
{
newNode.red = false;
}
//added
insertedNode = newNode;
grandParent = null;
greatGrandParent = null;
insertFix(newNode,parent,grandParent,greatGrandParent);
return newNode;
}
else if (value.CompareTo(rt.value) < 0)
{
rt.left = insertNode(rt.left, value, rt);
return rt;
}else //if(value.CompareTo(rt.value)> 0)
{
rt.right = insertNode(rt.right, value, rt);
return rt;
}
}
当我添加以下代码时,错误开始出现:
if (parent != null)
{
if (value > parent.value)
{
parent.right = newNode;
}
else {
parent.left = newNode;
}
}
// BNode类
class BNode
{
public int value;
public BNode left;
public BNode right;
public BNode parent; //check
public Boolean red = true; // red=false - indicates black
public BNode(int num, BNode parent)
{
value = num;
left = null;
right = null;
this.parent = parent;
}
}
在测试代码后,我添加了50,75,40,45,25 - 当我输入25时,发生了异常。