#include <stdio.h>
#include <stdlib.h>
#include <queue>
using namespace std;
char cache[101];
struct Node
{
char data;
struct Node * lchild,* rchild;
};
struct Node * root;
int cnt;
//构造二叉树
struct Node * Build_tree()
{
struct Node * root;
if(cache[cnt++] == ',') root = NULL;
else
{
root = (struct Node *)malloc(sizeof(struct Node));
root -> data = cache[cnt - 1];
root -> lchild = Build_tree();
root -> rchild = Build_tree();
}
return root;
}
//先序遍历
void xian(struct Node *root)
{
if(root != NULL)
{
printf("%c",root -> data);
xian(root -> lchild);
xian(root -> rchild);
}
}
//中序遍历
void zhong(struct Node *root)
{
if(root != NULL)
{
zhong(root -> lchild);
printf("%c",root -> data);
zhong(root -> rchild);
}
}
//后序遍历
void hou(struct Node *root)
{
if(root != NULL)
{
hou(root -> lchild);
hou(root -> rchild);
printf("%c",root -> data);
}
}
//叶子节点个数
int LeafCount (Node *root)
{
if(root==NULL)
return 0;
else
{
if(root->lchild==NULL&&root->rchild==NULL)
return 1;
else
return LeafCount(root->lchild)+LeafCount(root->rchild);
}
}
//二叉树高度
int height(Node *root)
{
int hl,hr,h;
if(root==NULL) return 0;
else
{
hl=height(root->lchild);
hr=height(root->rchild);
h=(hl>hr?hl:hr)+1;
}
return h;
}
//层次遍历
void levelOrder(Node *root)
{
queue<Node*>s;
if(root) {
printf("%c", root->data);
s.push(root);
while(!s.empty())
{
root = s.front();
s.pop();
if(root->lchild)
{
printf("%c", root->lchild->data);
s.push(root->lchild);
}
if(root->rchild)
{
printf("%c", root->rchild->data);
s.push(root->rchild);
}
}
}
}
int main()
{
while(scanf("%s",cache) != EOF)
{
cnt = 0;
root = Build_tree(); //建树
xian(root); //先序遍历
printf("\n");
zhong(root); //中序遍历
printf("\n");
hou(root);//后序遍历
printf("\n");
printf("%d\n",LeafCount(root)); //输出叶子节点个数
printf("%d\n",height(root)); //输出二叉树高度
levelOrder(root);//层次遍历
}
return 0;
}
二叉树模版
最新推荐文章于 2022-08-30 17:38:42 发布