【数据结构】二叉树的基本操作

一个月没更新博客了
1.二叉数的二叉链表储存表示

typedef struct BiTNode
{
    char data;
    struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

为了方便自己记忆,以及和前面学到的链表、栈、队列区分定义结构体(前面定义的结构体不需要写)*LinkList,他们(链表、栈、队列)只需要写LNode,就可以操作了,二叉树不行,二叉树需要用到二级指针,但是为什么用二级指针我现在还没有理解,等以后慢慢理解在更新这篇博客。现在先死记硬背,记住就行。

2.先序遍历建立二叉树

void CreateBiTree(BiTree *t)
{
    char ch;
    scanf("%c",&ch);
    if(ch=='@') *t=NULL;
    else
    {
        *t=(BiTNode *)malloc(sizeof(BiTNode));
        (*t)->data=ch;
        CreateBiTree(&(*t)->lchild);
        CreateBiTree(&(*t)->rchild);
    }
}

这里的CreateBiTree(&(*t)->lchild);,要记住用&(*t),地址的地址。慢慢理解,先记住。

3.后续遍历二叉树(递归算法)

void post_order_traverse(BiTree t)
{
    if(t)
    {
        post_order_traverse(t->lchild);
        post_order_traverse(t->rchild);
        printf("%c",t->data);
    }
}

4.中序遍历二叉树(递归算法)

void in_order_traverse(BiTree t)
{
    if(t)
    {
        in_order_traverse(t->lchild);
        printf("%c",t->data);
        in_order_traverse(t->rchild);
    }
}

非递归的算法我还没开始学,以后我会更新的!
遍历的形式参数要用BiTree t,操作比较简单。记下来,只有建立二叉树形式参数需要用二级指针即BiTree *t

5.计算二叉树的深度

int Depth(BiTree t)
{
    int ldepth=0,rdepth=0;
    if(t==NULL) return 0;
    else
    {
        ldepth=Depth(t->lchild);
        rdepth=Depth(t->rchild);
        if(ldepth>rdepth) return ldepth+1;
        else return rdepth+1;
    }
}

6.计算二叉树叶子节点个数

int LeafCount(BiTree *t)
{
    if((*t)==NULL) return 0;
    else
    {
        if((*t)->lchild==NULL&&(*t)->rchild==NULL) return 1;
        else return LeafCount(&(*t)->lchild)+LeafCount(&(*t)->rchild);
    }
}

可以用这种放法,也可以用BiTree t。这种编写起来比较麻烦,可以参考下一编写方式。

7.计算孩子兄弟法的二叉树的叶子节点

int CSLeafCount(BiTree t)
{
   if(t==NULL) return 0;
   if(t->lchild==NULL) return 1+CSLeafCount(t->rchild);
   else return CSLeafCount(t->rchild)+CSLeafCount(t->lchild);
}

当然,按照序号6函数操作,可以写为

int CSLeafCount(BiTree *t)
{
   if((*t)==NULL) return 0;
   if((*t)->lchild==NULL) return 1+CSLeafCount(&(*t)->rchild);
   else return CSLeafCount(&(*t)->rchild)+CSLeafCount(&(*t)->lchild);
}

这个写起来麻烦。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值