先序遍历、中序遍历、后序遍历,其实本质都是一样的
图片来源于传智播客课程
//求叶子节点个数,先序
int sum = 0;
void Ynumber(BinNode * root)
{
if (root)
{
if ((root->lchild == NULL) && (root->rchild == NULL))
{
sum++;
cout << "叶子" << sum << ":" << root->data << endl;
return;
}
if (root->lchild)
Ynumber(root->lchild);
if (root->rchild)
Ynumber(root->rchild);
}
}
//求叶子节点个数,先序,把num作为参数传进去
void Ynumber2(BinNode * root, int * const num)
{
if (root)
{
if ((root->lchild == NULL) && (root->rchild == NULL))
{
(*num)++;
cout << "叶子" << sum << ":" << root->data << endl;
return;
}
if (root->lchild)
Ynumber2(root->lchild,num);
if (root->rchild)
Ynumber2(root->rchild,num);
}
}
//求叶子节点个数,先序,把num作为参数传进去。num++语句段放哪里都一样,只是遍历时访问的时机不一样。
void Ynumber3(BinNode * root, int * const num)
{
if (root)
{
/*
if ((root->lchild == NULL) && (root->rchild == NULL))
{
(*num)++;
cout << "叶子" << sum << ":" << root->data << endl;
return;
}
*/
if (root->lchild)
Ynumber3(root->lchild, num);
if ((root->lchild == NULL) && (root->rchild == NULL))
{
(*num)++;
cout << "叶子" << sum << ":" << root->data << endl;
return;
}
if (root->rchild)
Ynumber3(root->rchild, num);
/*
if ((root->lchild == NULL) && (root->rchild == NULL))
{
(*num)++;
cout << "叶子" << sum << ":" << root->data << endl;
return;
}
*/
}
}
int main()
{
BinNode t1, t2, t3, t4, t5;
memset(&t1, NULL, sizeof(t1));
memset(&t2, NULL, sizeof(t2));
memset(&t3, NULL, sizeof(t3));
memset(&t4, NULL, sizeof(t4));
memset(&t5, NULL, sizeof(t5));
t1.data = 1;
t2.data = 2;
t3.data = 3;
t4.data = 4;
t5.data = 5;
t1.lchild = &t2;
t1.rchild = &t3;
t2.lchild = &t4;
t3.rchild = &t5;
//遍历
Preindex(&t1);
cout << endl;
Middleindex(&t1);
cout << endl;
Lastindex(&t1);
cout << endl;
//中序遍历求叶子节点个数,其他遍历相似
Ynumber(&t1);
cout << sum << endl;
int num = 0;
Ynumber2(&t1,&num);
cout << num << endl;
int num1 = 0;
Ynumber3(&t1, &num1);
cout << num1 << endl;
return 0;
}