【发布时间】:2013-04-10 18:54:43
【问题描述】:
对于可能在此类问题上需要帮助的此问题的未来查看者:我通过组合 2 个函数(InsertNode() 和 InTree())来修复它我不确定这是否是不好的做法,我会如果它确实确实解决了问题,或者只是掩盖了问题,请回复你们,但它似乎正在工作......
我查看了该网站(以及其他网站)上的各种答案,并从那些我得到的解决方案中得到了没有帮助的解决方案(尝试过但没有奏效,或者与我的程序没有区别)。 插入函数(我已将其隔离并认为这是有问题的代码)在某处有一些错误导致我的程序崩溃。
NP InTree(NP Node,NP Root)
{
if (Root == NULL)
{
Root=Node;
return Root;
}
else
{
if (Node->Input < Root->Input)
{
return InTree(Node,Root->Left);
}
else if (Node->Input > Root->Input)
{
return InTree(Node,Root->Right);
}
else
{
puts("Duplicate");
return NULL;
}
}
}
void InsertNode(int I, TP Tree)
{
NP Node;
Node=(NP)malloc(sizeof(struct AVLNode));
InitializeNode(Node);
Node->Input=I;
Node->Height=0;
Node->Left=NULL;
Node->Right=NULL;
InTree(Node,Tree->Root);
Tree->Size++;
}
NP 是节点指针,TP 是树指针
Node变量是通过InsertNode()发送的初始化节点
void InitializeTree(TP Tree)
{
Tree->Root=NULL;
Tree->Size=0;
}
void InitializeNode(NP Node)
{
Node->Input=0;
Node->Height=0;
}
以上是我的初始化函数,以防您需要查看它们。
树的内存在调用任何函数之前在主类中分配。
我通过测试看到的主要问题是,一旦 Root 等于 Node,它仍然为 null。
有什么办法可以解决这个问题吗?
【问题讨论】:
-
null 被用作标签,因为我的问题与保持为空的变量有关
-
应该更清楚一点.. NP 是代码中指向 Node 结构的指针: typedef Node* NP;
-
我认为基本上你可以尝试
Root = new NodeStruct; Root->Input = Node->Input而不是直接Root = Node。试试这个版本InTree(int v, NP Root)。
标签: c struct null binary-search-tree avl-tree