#include<bits/stdc++.h>
using namespace std;
typedef char TElemType;
typedef int Status;
typedef struct BNode{
TElemType data;
struct BNode *lchild,*rchild;
}BNode,*BTree;
char ch;
//先序遍历的顺序建立二叉树
void CreateBTree(BTree &T){
cin>>ch;
if(ch=='#') T=NULL;
else{
T=new BNode;
T->data=ch;
CreateBTree(T->lchild);
CreateBTree(T->rchild);
}
}
//先序遍历二叉树
void DLR(BTree T){
if(T){
cout<<T->data;
DLR(T->lchild);
DLR(T->rchild);
}
}
//中序遍历非递归
void LDRTraverse(BTree T){
stack<BTree> S;
BTree p,q;
p=T;
while(p||!S.empty()){
if(p){ //p非空
S.push(p);
p=p->lchild;
}
else{ //p为空
q=S.top();
S.pop();
cout<<q->data;
p=q->rchild;
}
}
}
//层次遍历二叉树
void Levelorder(BTree T){
if(T){
queue<BTree> q;
q.push(T);
while(!q.empty()){
if(q.front()->lchild) q.push(q.front()->lchild);
if(q.front()->rchild) q.push(q.front()->rchild);
cout<<q.front()->data;
q.pop();
}
}
}
//统计结点个数
int NCount(BTree T){
if(T==NULL){
return 0;
}
else return NCount(T->lchild)+NCount(T->rchild)+1;
}
//复制二叉树
void Copy(BTree T,BTree &NewT){
if(T=NULL){
NewT=NULL;
return;
}
else{
NewT=new BNode;
NewT->data=T->data;
Copy(T->lchild,NewT->lchild);
Copy(T->rchild,NewT->rchild);
}
}
//计算二叉树的深度
int Depth(BTree T){
if(T==NULL) return 0;
else{
int m=Depth(T->lchild);
int n=Depth(T->rchild);
if(m>n) return(m+1);
else return(n+1);
}
}
int main(){
BTree T;
cout<<"请选择:\n";
cout<<"1.建立二叉树\n";
cout<<"2.先序遍历二叉树\n";
cout<<"6.中序遍历二叉树非递归\n";
cout<<"7.层次遍历二叉树\n";
cout<<"8.二叉树的结点个数\n";
cout<<"9.复制二叉树\n";
cout<<"10.计算二叉树的深度\n";
int num;
cin>>num;
while(1){
switch(num){
case 1:
CreateBTree(T);
break;
case 2:
DLR(T);
cout<<endl;
break;
default:
cout<<"输入不合法,请重新输入\n";
}
cin>>num;
}
}
二叉树的遍历
最新推荐文章于 2025-12-27 16:49:17 发布
本文介绍了如何使用C++实现二叉树的创建、先序遍历、中序遍历非递归、层次遍历以及相关辅助函数,如节点计数、复制树和计算深度。适合理解二叉树基本操作的开发者。
17万+

被折叠的 条评论
为什么被折叠?



