关于递归和函数返回值的一个问题
下面一段代码:
//返回父亲结点 void *parent(NODE *&pNode,NODE *&p,NODE *head){ if(head!=NULL) { if(head->pLeft==pNode || head->pRight==pNode) { p=head; return p; //问:为什么这里必须要返回一个指针? } if(head->pLeft!=NULL) parent(pNode,p,head->pLeft); if(head->pRight!=NULL) parent(pNode,p,head->pRight); }}if(head->pLeft!=NULL) return parent(pNode,p,head->pLeft); if(head->pRight!=NULL) return parent(pNode,p,head->pRight);
[解决办法]
//返回父亲结点 void *parent(NODE *&pNode, NODE *head){ void *ret = NULL; if(head==NULL || pNode==NULL) //边界1 叶子节点 or pNode参数不对 { return ret; } //这里不知道你为什么这么做,如果你确定比较的是他们的地址。 if(head->pLeft==pNode || head->pRight==pNode) //边界2 找到节点 { return (void *)head; } if(head->pLeft != NULL) { ret = parent(pNode,p,head->pLeft); if(ret != NULL) { //找到节点直接返回剩下的不搜。 return ret; } } if(head->pRight!=NULL) { ret = parent(pNode,p,head->pRight); if(ret != NULL) { //找到节点直接返回剩下的不搜。 return ret; } } return ret; //找不到节点。}