二叉树基本操作

二叉树的建立,前序遍历,中序遍历,后序遍历以及求深度和叶子节点个数

#include
#include
#include<malloc.h>

typedef struct TreeNode{
    int data;
    struct TreeNode *left,*right;
}BiNode,*BiTree;

BiTree Create()
{
    int val;
    scanf("%d",&val);
    if(val<=0)
        return NULL;
    BiTree root=(BiTree)malloc(sizeof(BiNode));
    if(!root)
        printf("Failed\n");
    if(val>0)
    {
        root->data=val;
        root->left=Create();
        root->right=Create();
        return root;
    }
}

void PreOrder(BiTree root)
{
    if(root==NULL)
        return;
    printf("%d\t",root->data);
    PreOrder(root->left);
    PreOrder(root->right);
}

void InOrder(BiTree root)
{
    if(root==NULL)
        return;
    InOrder(root->left);
    printf("%d\t",root->data);
    InOrder(root->right);
}

void PostOrder(BiTree root)
{
    if(root==NULL)
        return;
    PostOrder(root->left);
    PostOrder(root->right);
    printf("%d\t",root->data);
}

int maxDepth(BiTree root)
{
    if(root==NULL)
        return 0;
    int maxleft=maxDepth(root->left);
    int maxright=maxDepth(root->right);
    if(maxleft>maxright)
        return maxleft+1;
    else
        return maxright+1;
}

int LeafNodeNum(BiTree root)
{
    if(root==NULL)
        return 0;
    if(root->left==NULL&&root->right==NULL)
        return 1;
    else
        return LeafNodeNum(root->left)+LeafNodeNum(root->right);
}
int main(void)
{
    BiTree root=(BiTree)malloc(sizeof(BiNode));
    root=Create();
    printf("pre\n");
    PreOrder(root);
    printf("\nIn\n");
    InOrder(root);
    printf("\npost\n");
    PostOrder(root);
    printf("\ndepth :%d\n",maxDepth(root));
    printf("leafnum\n:%d\n",LeafNodeNum(root));
    system("pause");
    return 0;
}

二叉树基本操作_第1张图片

 

你可能感兴趣的:(二叉树基本操作)