//Author:PanDaoxi
#include <iostream>
using namespace std;
struct node{
int left,right; //左孩子和右孩子
char value; //值
}data[101];
int root=0,cnt; //根节点和记录有效字符
char ch; //输入的数据
//构建二叉树
int buildTree(int bt){
//参数:结点的编号
cin>>ch;
if(ch=='.'){
//判断是否为空结点
bt=0; //赋值为0
return bt; //跳出程序
}
else{
//非空结点,进行先序遍历
bt=++cnt; //构造结点
data[bt].value=ch; //存放根的值
data[bt].left=data[bt].right=0; //左右孩子都归零
data[bt].left=buildTree(bt); //递归左子树
data[bt].right=buildTree(bt); //递归右子树
}
return bt; //完成递归
}
//后序遍历二叉树
void postorder(int bt){
if(bt){
//非空结点
//递归输出根
postorder(data[bt].left);
postorder(data[bt].right);
cout<<data[bt].value;
}
}
//先序遍历
void preorder(int bt){
if(bt){
cout<<data[bt].value;
preorder(data[bt].left);
preorder(data[bt].right);
}
}
//中序遍历
void inorder(int bt){
if(bt){
inorder(data[bt].left);
cout<<data[bt].value;
inorder(data[bt].right);
}
}
int main(){
root=buildTree(0); //构建二叉树
cout<<"后序:";
postorder(root);
cout<<endl<<"中序:";
inorder(root);
cout<<endl<<"先序:";
preorder(root);
cout<<endl;
return 0;
}
C++遍历输出二叉树
猜你喜欢
转载自blog.csdn.net/PanDaoxi2020/article/details/120934941
今日推荐
周排行