用的递归的方法查找元素 有点类似于二叉树建立
代码如下
struct node *search(struct node *n,int v){//查找
struct node *p;
p=n;
if(p->value==v){//找到
return p;
}
else if(v<p->value){//左边部分查找
if(p->left==NULL)
return NULL;//未找到
else{
p=p->left;
search(p,v);
}
}
else{//v>p->value,右边部分查找
if(p->right==NULL)
return NULL;//未找到
else{
p=p->right;
search(p,v);
}
}
}
main方法中:point=search(root,20);
用这种方法 总是返回根节点的值 而不是要查找的值或者null
因为你需要修改指针的地址,所以你需要用二级指针
struct node *search(struct node **n,int v)
struct node **p;
参考这个代码
int
Search_data(TreeNode *t,TreeNode **p,TreeNode **q, elemtype x)
{
int flag=0;
*p=NULL;
*q=t;
while(*q)
{
if (x>(*q)->data)
{
*p=*q;
*q=(*q)->Rchild;
}
else{
if (x<(*q)->data)
{
*p=*q;
*q=(*q)->Lchild;
}
else{
flag=1;
break;
}
}
}
return flag;
}
在左边和右边部分查询的if里你漏了return,应该是:
return search(p, v);
而不是
search(p,v);
不是直接这样就好了,搞那么复杂干嘛
status search(ptree t,ptree &p,char ch)
{
if(t == NULL)
return !OK;
if (t->data == ch) {
p = t;
return OK;
}
if(!search(t->lchild,p,ch))
search(t->rchild, p, ch);
}
不是直接这样就好了,搞那么复杂干嘛
status search(ptree t,ptree &p,char ch)
{
if(t == NULL)
return !OK;
if (t->data == ch) {
p = t;
return OK;
}
if(!search(t->lchild,p,ch))
search(t->rchild, p, ch);
}