二叉树的建立与遍历,叶子结点的数目以及树的深(3)
发布时间:2021-06-06
发布时间:2021-06-06
二叉树的建立与遍历,叶子结点的数目以及树的深度的求法,采用递归求解
n h2+1;
}
//***********************************************************************************
//二叉树的消毁操作
template<class T>
BTNode<T>* destroy(BTNode<T>* p) //消毁函数,用来消毁二叉树中的各个结点
{
if(p)
{
return destroy(p->Lchild);
return destroy(p->Rchild);
delete p;
}
}
//********************************************************************************
//主函数的设计
int main ()
{
BTNode<int> * rootNode = NULL;
int choiced = 0;
while(true)
{
system("cls");
cout<<"\n\n\n ---主界面---\n\n\n";
cout<<" 1、创建二叉树 2、先序遍历二叉树\n";
cout<<" 3、中序遍历二叉树 4、后序遍历二叉树\n";
cout<<" 5、统计结点总数 6、查看树深度 \n";
cout<<" 7、消毁二叉树 0、退出\n\n";
cout<<" 请选择操作:";
cin>>choiced;
if(choiced == 0)
return 0;
else if(choiced == 1)
{
system("cls");
cout<<"请输入每个结点,回车确认,并以-1结束:\n";
createBinTree(rootNode );
}
else if(choiced == 2)
{
system("cls");
cout<<"先序遍历二叉树结果:\n";
preOrder(rootNode);
cout<<endl;
system("pause");
}
else if(choiced == 3)
{
system("cls");
cout<<"中序遍历二叉树结果:\n";
inOrder(rootNode);
cout<<endl;
system("pause");
}
else if(choiced == 4)
{
system("cls");
cout<<"后序遍历二叉树结果:\n";
levelOrder(rootNode);
cout<<endl;
system("pause");
}
else if(choiced == 5)
{
system("cls");
int count = countNode(rootNode);
cout<<"二叉树中结点总数为"<<count<<endl;
system("pause");
}
else if(choiced == 6)
{
system("cls");
int dep = depth(rootNode);
cout<<"此二叉树的深度为"<<dep<<endl;
system("pause");
}
else if(choiced == 7)
{
system("cls");
cout<<"二叉树已被消毁!\n";
destroy(rootNode);
cout<<endl;
system("pause");
}
else
{
system("cls");
cout<<"\n\n\n\n\n\t错误选择!\n";
}
}
}
如 5
/ \
3
下一篇:医学专业毕业实习报告