求树中是否存在路径和等于给出的特定值

bool haspathsum(BTNode *p,int sum)
{
    if(p=NULL)
        return false;            //树空一定错误
    if(p->lchild==NULL&&p->rchild==NULL) 
        return p->data==sum;      //树的左右子树空,比较根节点的数据是否与sum相同
    return haspathsum(p->lchild,sum-p->data)||haspathsum(p->rchild,sum-p->data);  
}

猜你喜欢

转载自blog.csdn.net/m0_47575628/article/details/108968455