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

//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");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值