二叉树遍历的应用

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值