您的位置:首页 > 编程语言 > C语言/C++

C语言笔试题(16)——二叉树基本算法

2012-09-09 09:50 417 查看
#include <stdio.h>
#include <stdlib.h>

struct node 
{
    char data;
    struct node *lchild, *rchild;
};

//根据前序遍历创建二叉树('.'代表为空的结点)
//输入124...35...验证 
struct node *create_tree(void)     
{
    struct node *root;
    char x;
    
    x = getchar();
 
    if (x == '.')
        root = NULL;
    else
    {
        root = (struct node *)malloc(sizeof(struct node));
        root->data = x;

        root->lchild = create_tree();
        root->rchild = create_tree();
    }

    return root;
}

//前序遍历
void print_pre(struct node *root)
{
    if (root == NULL)
        return ;
    else
    {
        printf("%c ", root->data);
        print_pre(root->lchild);
        print_pre(root->rchild);
    }

    return;
}

//中序遍历
void print_in(struct node *root)
{
    if (root == NULL)
        return ;
    else
    {
        print_in(root->lchild);
        printf("%c ", root->data);
        print_in(root->rchild);
    }

    return;
}

//后序遍历
void print_post(struct node *root)
{
    if (root == NULL)
        return ;
    else
    {
        print_post(root->lchild);
        print_post(root->rchild);
        printf("%c ", root->data);
    }

    return ;
}

//统计叶子节点
int countleaf(struct node *root)
{
    int num = 0;

    if (root != NULL)
    {
        if (root->lchild == NULL && root->rchild == NULL)
            return 1;
        else
            return (countleaf(root->lchild) + countleaf(root->rchild));
    }
}

//计算二叉树的深度
int treedepth(struct node *root)
{
    int h, lh, rh;

    if (root == NULL)
        h = 0;
    else
    {
        lh = treedepth(root->lchild);
        rh = treedepth(root->rchild);

        if (lh >= rh)
            h = lh + 1;
        else
            h = rh + 1;
    }

    return h;
}

//统计度为1的结点
int count1(struct node *root)
{
    int num = 0;

    if (root != NULL)
    {
        if (root->lchild != NULL && root->rchild != NULL)
            num = (count1(root->lchild) + count1(root->rchild) );

        if ((root->lchild == NULL && root->rchild != NULL) || (root->lchild != NULL && root->rchild == NULL))
            num = (count1(root->lchild) + count1(root->rchild) + 1);

        return num;
    }
}

int main(int argc, const char *argv[])
{
    struct node *root;
    struct node *p;

    root = create_tree();
    print_pre(root);
    printf("\n");
    print_in(root);
    printf("\n");
    print_post(root);
    printf("\n");

    printf("count : %d\n", countleaf(root));
    printf("depth: %d\n", treedepth(root));
    printf("count1 : %d\n", count1(root));

    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: