#include <iostream>
using namespace std;
const int Maxsize = 100;
struct Node
{
int data;
Node*lchild,*rchild;
};
class Tree
{
public:
Tree(){cout << "输入节点信息,如果是空请输入“#”" << endl;
root = Creat(root); }
void PreOrder(){cout <<"前序遍历得到:";PreOrder(root); cout<<endl;}
int Depth(){cout <<"二叉树的深度是:"<<Depth(root)<<endl;}
void Count(){Count(root); cout << "二叉树的结点数是:" << count << endl;} //计算二叉树节点数
void Exchange(){Exchange(root);cout<<"把左右子树进行交换"<<endl;} //把二叉树左右子树进行交换
void LeverOrder(); //再次层序遍历
private:
int count = 0;
Node*root;
Node*Creat(Node*root);
void PreOrder(Node *root);
int Depth(Node *root);
void Count(Node *root);
void Exchange(Node*root);
};
//实现构建一颗二叉树
Node*Tree::Creat(Node*root)
{
char ch;
cin >> ch;
if (ch == '#')root = NULL;
else{
root = new Node;
root->data = ch;
root->lchild = Creat(root->lchild);
root->rchild = Creat(root->rchild);
}
return root;
}
//实现前序遍历
void Tree::PreOrder(Node *root)
{
if(root==NULL)return;
else{
cout<<root->data;
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
int Tree::Depth(Node *root)//求二叉树深度
{
int hl=0,hr=0;
if(root==NULL)return 0;
else{
hl=Depth(root->lchild);
hr=Depth(root->rchild);
return max(hl,hr)+1;
}
}
void Tree::Count(Node *root)//实现求二叉树叶子节点数
{
if(root!=NULL)
{
Count(root->lchild);
count++;
Count(root->rchild);
}
}
void Tree::Exchange(Node*root)//交换左右子树
{
Node *t;
if(root!=NULL){
Exchange(root->lchild);
Exchange(root->rchild);
t=root->lchild;
root->lchild=root->rchild;
root->rchild=t;
}
}
//层序遍历
void Tree::LeverOrder()
{cout<<"层序遍历:";
int rear,front;
Node *Q[50];
Node *q;
front=rear=-1;
if(root==NULL)return;
Q[++rear]=root;
while(front!=rear)
{
q=Q[++front];
cout<<q->data;
if(q->lchild!=NULL)Q[++rear]=q->lchild;
if(q->rchild!=NULL)Q[++rear]=q->rchild;
}
}
int main()
{
Tree B;
B.PreOrder();
B.Depth();
B.Count();
B.Exchange();
B.LeverOrder();
return 0;
}
二叉树遍历全都是出ASCII码
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
6条回答 默认 最新
相关推荐 更多相似问题
点击登录
提问题
悬赏问题
- ¥15 如何修改为正确的?求解决
- ¥15 django访问管理员界面问题
- ¥20 python homework完成
- ¥20 求解 多变量系统的最小二乘辨识问题的推导以及matlab仿真
- ¥15 arduino esp8266 Blinker编译报问题
- ¥15 ubuntu18.04运行模型,直接死机
- ¥30 (问卷调查)莫名其妙丢了u盘,你们会是什么心理状态
- ¥100 Spark+android应⽤案例
- ¥15 yolov8 目标检测 重叠 遮挡
- ¥20 微信聊天记录如何部署到服务器上