#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
typedef struct node{
char data;
node * lchild;
node * rchild;
}BTree;
typedef struct{
BTree * data[MAXSIZE];
int top;
}SeqStack;
BTree * create(BTree * p){
char ch;
scanf("%c",&ch);
if(ch != ' '){
p = (BTree *)malloc(sizeof(BTree));
p->data = ch;
p->lchild = create(p->lchild);
p->rchild = create(p->rchild);
return p;
}else{
return NULL;
}
}
//先序遍历二叉树
void preorder(BTree * p,SeqStack * s){
while(p != NULL || s->top != -1){
if(p!=NULL){
s->top++;
printf("%4c",p->data);
s->data[s->top] = p;
p = p->lchild;
}else{
p = s->data[s->top];
s->top--;
p = p->rchild;
}
}
}
//在二叉树中查找某个元素
BTree * search(BTree * p,SeqStack * s,char x){
while(p != NULL || s->top != -1){
if(p!=NULL){
if(p->data == x){
return p;
}else{
s->top++;
s->data[s->top] = p;
p = p->lchild;
}
}else{
p = s->data[s->top];
s->top--;
p = p->rchild;
}
}
return NULL;
}
//统计叶子节点的个数
int leaf(BTree * p){
if(p == NULL){
return 0;
}else if(p->lchild == NULL && p->rchild == NULL){
return 1;
}else{
return(leaf(p->lchild) + leaf(p->rchild));
}
}
//求二叉树的深度
int height(BTree * p){
int lheight,rheight;
if(p == NULL){
return 0;
}else{
lheight = height(p->lchild);
rheight = height(p->rchild);
return lheight > rheight ? (lheight + 1) : (rheight + 1);
}
}
int main(){
SeqStack * s = (SeqStack *)malloc(sizeof(SeqStack));
s->top = -1;
BTree * p,* temp;
int num;
int h;
p = create(p);
printf("preorder:\n");
preorder(p,s);
printf("\n");
temp = search(p,s,'o');
if(temp == NULL){
printf("The element is not found!\n");
}else{
printf("The element is:%c",temp->data);
}
printf("\n");
num = leaf(p);
printf("The total number of the leaves is:%d\n\n",num);
h = height(p);
printf("The depth of the tree is:%d\n",h);
return 0;
}
二叉树遍历的应用
最新推荐文章于 2022-01-10 10:55:45 发布