赞
踩
以此树为例:
int getNodeNumRec(BiTree* T) {
if (T == NULL)
{
return 0;
}
else
{
return getNodeNumRec(T->lchild) + getNodeNumRec(T->rchild) + 1 ;
}
}
int getNodeNumLeafRec(BiTree* T) {
if (T == NULL)
{
return 0;
}
if (T->lchild == NULL && T->rchild == NULL) //如果是叶子结点,则返回1
{
return 1;
}
return getNodeNumLeafRec(T->lchild) + getNodeNumLeafRec(T->rchild);
}
int getNodeNumOneRec(BiTree* T) { if (T == NULL) { return 0; } if ((T->rchild == NULL && T->lchild != NULL) || (T->lchild == NULL && T->rchild != NULL)) { return getNodeNumOneRec(T->lchild) + getNodeNumOneRec(T->rchild) + 1; } else { return getNodeNumOneRec(T->lchild) + getNodeNumOneRec(T->rchild); } }
int getNodeNumTwoRec(BiTree* T) { if (T == NULL) { return 0; } if (T->lchild && T->rchild) { return getNodeNumTwoRec(T->lchild) + getNodeNumTwoRec(T->rchild) + 1; } else { return getNodeNumTwoRec(T->lchild) + getNodeNumTwoRec(T->rchild); } }
int getNodeNumLevelRec(BiTree* T, int k) {
if (T == NULL || k < 1)
{
return 0;
}
if (k == 1)
{
return 1;
}
return getNodeNumLevelRec(T->lchild, k - 1) + getNodeNumLevelRec(T->rchild, k - 1);
}
cout << "所有节点:" << getNodeNumRec(T) << endl;
cout << "度为2的节点:" << getNodeNumTwoRec(T) << endl;
cout << "度为1的节点:" << getNodeNumOneRec(T) << endl;
cout << "度为0的节点:" << getNodeNumLeafRec(T) << endl;
cout << "第4层的节点:" << getNodeNumLevelRec(T,4) << endl;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。