数据结构——二叉树的宽度【非递归算法与层次遍历】(C语言)

宽度:同一层最大结点数

  • 层次遍历与树的宽度非递归算法求解
  • 此处用到了< queue >为C++语言STL的队列库,其操作原理与队列相同。
#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include <iostream>
#define MAXSIZE   10010
#define ElemType int
using namespace std;
typedef struct BTNode{
    ElemType data;
    BTNode *lchild,*rchild;
}*BTree;
//先序建树
BTree CreateTree(){
    ElemType ch;
    printf("输入结点元素值:");
    scanf("%d",&ch);
    if(ch == 0)
        return NULL;
    else{
        BTree tree=(BTree)malloc(sizeof(BTree));
        tree->data=ch;
        printf("%d 结点左子树\n",ch);
        tree->lchild=CreateTree();
        printf("%d 结点右子树\n",ch);
        tree->rchild=CreateTree();
        return tree;
    }
}
//层次遍历
void LayeredOrderTravel(BTree tree){
    queue<BTree> queue1;
    BTree p;
    if(tree){//树非空
        //入队与队列指针(下标)初始化
       queue1.push(tree);
       while(!queue1.empty()){//队列非空
            p=queue1.front();//队头元素出队并访问
            queue1.pop();
            printf("%d ",p->data);//访问
            if(p->lchild)//左孩子不为空则入队
                queue1.push(p->lchild);
            if(p->rchild)//右孩子不为空则入队
                queue1.push(p->rchild);
       }
    }
}
int getDepth(BTree tree){
    if(!tree)
        return 0;
    else{
        int leftDepth=getDepth(tree->lchild);
        int rightDepth=getDepth(tree->rchild);
        return leftDepth > rightDepth ? (leftDepth+1):(rightDepth+1);
    }
}
//计算树的宽度(结点最多的那一层的结点总个数)
int getWidth(BTree tree){
    if(!tree)
        return 0;
    queue<BTree> queue1;
    BTree p;
    int maxWidth=1,lastWidth=0,templateWidth=0;
    if(tree){//树非空
        //入队与队列指针(下标)初始化
       queue1.push(tree);
       lastWidth=1;
       while(!queue1.empty()){//队列非空[未遍历完所有结点]
          templateWidth=lastWidth;
          while(templateWidth){//当前层所有结点
            p=queue1.front();//队头元素出队并访问
            queue1.pop();
            //printf("%d ",p->data);
            if(p->lchild)
                queue1.push(p->lchild);
            if(p->rchild)
                queue1.push(p->rchild);
            templateWidth--;//取出队头元素【上一层元素】,记录的上一层结点的宽度减一
          }//while
          int nowWidth=queue1.size();
          maxWidth= nowWidth > maxWidth ? nowWidth : maxWidth;
          lastWidth= nowWidth;
       }//while
    }//if
    return  maxWidth;
}
int main(){
    printf("二叉树的建立\n");
    BTree tree;
    tree=CreateTree();
    printf("二叉树的层序遍历\n");
    LayeredOrderTravel(tree);
    printf("\n获取二叉树深度\n");
    int maxDepth=0,maxWidth=0;
    maxDepth=getDepth(tree);
    printf("树的深度为:%d\n",maxDepth);
    printf("\n非递归算法获取二叉树宽度\n");
    maxWidth=getWidth(tree);
    printf("树的宽度为:%d\n",maxWidth);
    return 0;
}

在这里插入图片描述在这里插入图片描述

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值