二叉树的层序遍历——题集(七)
今天分享一下二叉树的层序遍历,并判断N的阶乘的末尾有多少个0。
实现一颗二叉树的层序遍历的源代码和运行示例如下。
源代码如下:
#include<iostream>
using namespace std;
#include<queue>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
void Print(TreeNode* pRoot) {//层序遍历
queue<TreeNode*> cur;//利用队列先进先出的特性实现二叉树的层序遍历
if(pRoot==NULL) return ;
cur.push(pRoot);
while(!cur.empty()){
TreeNode* point=cur.front();
cur.pop();
cout<<point->val<<" ";
if(point->left != NULL)
cur.push(point->left);
if(point->right != NULL)
cur.push(point->right);
}
cout<<endl;
return;
}
void TestPrintST(){//层序遍历
TreeNode pRoot1(1);
TreeNode pRoot2(2);
TreeNode pRoot3(3);
TreeNode pRoot4(4);
TreeNode pRoot5(5);
TreeNode pRoot6(6);
TreeNode pRoot7(7);
pRoot1.left = &pRoot2;
pRoot1.right = &pRoot3;
pRoot2.left = &pRoot4;
pRoot2.right = &pRoot5;
pRoot3.left = &pRoot6;
pRoot3.right = &pRoot7;
cout<<"层序遍历二叉树"<<endl;
Print(&pRoot1);//层次打印和之字打印可共用
}
int main(){
TestPrintST();//层序遍历
system("pause");
return 0;
}
运行结果:
给定一个整数N,那么N的阶乘N!末尾有多少个0呢?
例如:N=10,N!=3 628 800,N!的末尾有两个0。
源代码和运行示例如下示:
源代码如下:
#include<iostream>
using namespace std;
int Endofone(int N){//阶乘N!末尾有多少个0
long long sum=1;
int num=0;
cout<<N;
while(N>0){
sum*=N;
N--;
}
cout<<"的阶乘为: "<<sum<<endl;
while(sum%10 == 0){
num++;
sum/=10;
}
return num;
}
int main(){
cout<<"求N的阶乘末尾有多少个0!"<<endl<<endl;
cout<<"0的阶乘的末尾有多少0->"<<Endofone(0)<<endl;//阶乘N!末尾有多少个0
cout<<"10的阶乘的末尾有多少0->"<<Endofone(10)<<endl;
cout<<"20的阶乘的末尾有多少0->"<<Endofone(20)<<endl;
system("pause");
return 0;
}
运行结果:
分享如上,如有错误,望斧正!愿大家学得开心,共同进步!