二叉树基本操作

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

#include<windows.h>
#include<stdio.h>
#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
");
    if(val>0)
    {
        root->data=val;
        root->left=Create();
        root->right=Create();
        return root;
    }
}

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

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

void PostOrder(BiTree root)
{
    if(root==NULL)
        return;
    PostOrder(root->left);
    PostOrder(root->right);
    printf("%d	",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
");
    PreOrder(root);
    printf("
In
");
    InOrder(root);
    printf("
post
");
    PostOrder(root);
    printf("
depth :%d
",maxDepth(root));
    printf("leafnum
:%d
",LeafNodeNum(root));
    system("pause");
    return 0;
}

原文地址:https://www.cnblogs.com/wangtianning1223/p/11625128.html