二叉树的插入方法
有什么区别
[ insert_node(&(tmp->left),value);] VS [ tmp=tmp->right; insert_node(&(tmp),值);]
void insert_node(struct btree **bt,int value)
{
btree *tmp= *bt, *r ;
if(*bt==NULL)// first node
{
(*bt)=(struct btree *)malloc(sizeof(btree));
(*bt)->data=value;
(*bt)->left=NULL;
(*bt)->right=NULL;
}
else
{
if(value > tmp->data)
insert_node(&(tmp->right),value);
else
insert_node(&(tmp->left),value);
}
#if 0 //start
OR /** COMMENT START
earlier I had below piece of code but not working
can any please explain what's the difference in
insert_node(&(tmp->left),value); VS [ tmp=tmp->right; insert_node(&(tmp),value);]
COMMENT END **/
else
{
if(value > tmp->data)
tmp=tmp->right;
else
tmp=tmp->left ;
insert_node(&tmp,value);
}
#endif //end
}
what's the difference in
[ insert_node(&(tmp->left),value);] VS [ tmp=tmp->right; insert_node(&(tmp),value);]
void insert_node(struct btree **bt,int value)
{
btree *tmp= *bt, *r ;
if(*bt==NULL)// first node
{
(*bt)=(struct btree *)malloc(sizeof(btree));
(*bt)->data=value;
(*bt)->left=NULL;
(*bt)->right=NULL;
}
else
{
if(value > tmp->data)
insert_node(&(tmp->right),value);
else
insert_node(&(tmp->left),value);
}
#if 0 //start
OR /** COMMENT START
earlier I had below piece of code but not working
can any please explain what's the difference in
insert_node(&(tmp->left),value); VS [ tmp=tmp->right; insert_node(&(tmp),value);]
COMMENT END **/
else
{
if(value > tmp->data)
tmp=tmp->right;
else
tmp=tmp->left ;
insert_node(&tmp,value);
}
#endif //end
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在非工作情况下,您将向其提供
tmp
变量的地址,从而更新该指针,该指针位于堆栈上并且不会用于任何用途。在工作情况下,您将给出 bt 节点中实际指针的地址,这就是您想要的。
In the non-working case, you are giving it the address of your
tmp
variable, and therefore updating that pointer, which is on your stack and not going to be used for anything.In the working case, you are giving the address of the actual pointer in your bt node which is what you want.
没有语义差异。 #2 将下一个节点存储在局部变量中,该变量将是一个寄存器,而 #1 将节点存储到寄存器中,但它不能作为局部变量使用。
如果需要再次访问该值,请使用#2。
There is no semantic difference. #2 is storing the next node in a local variable, which will be a register, whereas #1 is storing the node into the register, but it won't be available as a local variable.
If you need to access the value again, use #2.