二叉树

二叉树创建及相关操作

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct BiNode
{
    char data;
    struct BiNode *left,*right;
}node,*bitree;


bitree CREAT()  //先序创建二叉树
{
    char a;
    bitree newnode;
    scanf("%c", &a);
    if(a == '#')
        return NULL;
    else
    {
        newnode = (bitree)malloc(sizeof(node));
        newnode->data = a;
        newnode->left = CREAT();
        newnode->right = CREAT();
    }
    return newnode;
}
void print(bitree p)  //中序输出二叉树
{
    if(p == NULL)
        return;
    else
    {
        print(p->left);
        printf("%c ",p->data);
        print(p->right);
    }
}

int btreedepth(bitree bt)
{
    int ldepth,rdepth;
    if(bt == NULL)
        return 0;
    else
    {
        ldepth = btreedepth(bt->left);
        rdepth = btreedepth(bt->right);
        return (ldepth > rdepth ? ldepth+1 : rdepth+1); //这个位置是可以是它与左右结点的关系。
    }
}

int ncount(bitree bt)
{
    if(bt == NULL)
        return 0;
    else
        return(ncount(bt->left) + ncount(bt->right) + 1);
}

int lcount(bitree bt)
{
    if(bt == NULL)
        return 0;
    else if(bt->left == NULL && bt->right == NULL)
        return 1;
    else
        return (lcount(bt->left) + lcount(bt->right));
}
int main()
{
    bitree route = (bitree)malloc(sizeof(node));
    printf("please input nodes:\n");
    route = CREAT();
    printf("the preorder traversal is:\n");
    print(route);
    printf("\nthe depth of the tree is: %d",btreedepth(route));
    printf("\nthe counts of node is: %d", ncount(route));
    printf("\nthe leaf counts of node is : %d", lcount(route));
    return 0;
}

二叉树

二叉树二叉树 ever_promise 发布了29 篇原创文章 · 获赞 5 · 访问量 643 私信 关注
上一篇:4.3二叉树的遍历王道数据例程实现


下一篇:二叉树的三种遍历方式