#include <bits/stdc++.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef struct BTNode{
char data;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode;
//递归创建一棵二叉树
int i = 0;
void create_Tree(BTNode *&p,char a[]){
char t;
t = a[i++];
if(t == '0')
p = NULL;
else{
p = new BTNode;//申请存储空间
p->data = t;
create_Tree(p->lchild,a);
create_Tree(p->rchild,a);
}
}
//先序遍历
void preOrder(BTNode *p){
if(p){
cout<<p->data<<" ";
preOrder(p->lchild);
preOrder(p->rchild);
}
}
//中序遍历
void inOrder(BTNode *p){
if(p){
inOrder(p->lchild);
cout<<p->data<<" ";
inOrder(p->rchild);
}
}
//后序遍历
void postOrder(BTNode *p){
if(p){
postOrder(p->lchild);
postOrder(p->rchild);
cout<<p->data<<" ";
}
}
//计算叶子结点个数
int count(BTNode *p){
if(p == NULL)
return 0;
if(p->lchild == NULL && p->rchild == NULL)
return 1;
return (count(p->lchild)+count(p->rchild));
}
//计算结点个数
int n = 0;
int count2(BTNode *p){
if(p == NULL)
return 0;
else
return 1+count2(p->lchild)+count2(p->rchild);
}
//计算二叉树的深度
int deep(BTNode *p){
int depl,depr;
if(p == NULL)
return 0;
else{
depl = deep(p->lchild);
depr = deep(p->rchild);
return 1+(depl>depr?depl:depr);
}
}
int main(int argc, char** argv) {
char a[100];
char b[100];
gets(a);
int lc = strlen(a);
//cout<<"字符个数:"<<lc<<endl;
int j = 0;
for(int i = 0;i < lc;++i)
if(a[i] != ' ')
b[j++] = a[i];
int lb = strlen(b);
//cout<<lb<<endl;
BTNode *p;
create_Tree(p,b);
preOrder(p);
cout<<endl;
inOrder(p);
cout<<endl;
postOrder(p);
cout<<endl;
int c = count(p);
cout<<c<<endl;
// int m = count2(p);
// cout<<m<<endl;
// int d = deep(p);
// cout<<d<<endl;
return 0;
}
瑞士军刀
最新推荐文章于 2025-04-25 21:12:48 发布