先序,中序,后序,求叶子结点数,深度,拷贝,几种二叉树的常见递归使用方法

//vs2015 编译通过.

#include "stdio.h"
#include "stdlib.h"
#include "string.h"


typedef struct Node
{
    int data;
    struct Node *lchild, *rchild;
}BiNode , *BiTree;



//中序
void  inOrder(BiNode *root)
{
    if (root!=NULL)
    {
        inOrder(root->lchild);
        printf("data:%d \n", root->data);
        inOrder(root->rchild);
    }
}

//后序
void  postOrder(BiNode *root)
{
    if (root != NULL)
    {
        postOrder(root->lchild);
        postOrder(root->rchild);
        printf("data:%d \n", root->data);
    }
}

//先序
void  preOrder(BiNode *root)
{
    if (root != NULL)
    {
        printf("data:%d \n", root->data);
        preOrder(root->lchild);
        preOrder(root->rchild);
    }
}




//求叶子数
//叶子的概念就是 左右节点都是空
void  getLeafNum(BiNode *root,int  *num)
{
    if (root != NULL)
    {
        printf("data:%d \n", root->data);
        if (root->lchild ==NULL && root->rchild==NULL)
        {
            (*num)++;
        }
        getLeafNum(root->lchild,num);
        getLeafNum(root->rchild,num);
    }
}



int GetDepth(BiNode *root)
{
    if (root!=NULL)
    {

        int left = 1;
        int right = 1;

        left += GetDepth(root->lchild);
        right += GetDepth(root->rchild);
        return left > right ? left : right;
    }
    return 0;
}



//拷贝一个树
BiNode *copyTree(BiNode *T)
{
    BiNode *newLptr = NULL;
    BiNode *newRptr = NULL;
    BiNode *newNode = NULL;

    if (T->lchild!=NULL)
    {
        newLptr = copyTree(T->lchild);
    }

    if (T->rchild !=NULL)
    {
        newRptr = copyTree(T->lchild);
    }

    newNode = (BiNode *)malloc(sizeof(BiNode));
    if (newNode==NULL)
    {
        return NULL;
    }
    newNode->lchild = newLptr;
    newNode->rchild = newRptr;
    newNode->data = T->data;
    return newNode;
}



void main()
{

    BiNode t1, t2, t3, t4, t5;
    memset(&t1, 0, sizeof(BiNode));
    memset(&t2, 0, sizeof(BiNode));
    memset(&t3, 0, sizeof(BiNode));
    memset(&t4, 0, sizeof(BiNode));
    memset(&t5, 0, sizeof(BiNode));

    t1.data = 1;
    t2.data = 2;
    t3.data = 3;
    t4.data = 4;
    t5.data = 5;

    t1.lchild = &t2;
    t1.rchild = &t3;
    t2.lchild = &t4;
    t3.lchild = &t5;

    printf("中序\n"); 
    inOrder(&t1);
    printf("前序\n");
    preOrder(&t1);
    printf("后 序\n");
    postOrder(&t1);
    int num = 0;

    getLeafNum(&t1, &num);
    printf("leaf num%d \n", num);


    printf("depth :%d\n",GetDepth(&t1));

    {
            //拷贝一个树
        BiNode *newtree = NULL;
        newtree =copyTree(&t1);

    }


    system("pause");
}

你可能感兴趣的:(二叉树)