二叉树的宽度C实现(非递归)

采用层次遍历的方式,使用一个队列,每层的结点依次入队,出队,统计宽度,比较该层宽度与前k层最大宽度的大小。

typedef int DataType;
struct Node
{
    DataType data;
    struct Node *leftChild;
    struct Node *rightChild;
};
typedef struct Node BiTreeNode,*BiTree;

typedef struct QNode
{
    BiTreeNode *addr;
    struct QNode *link;
}qnode;

int Width_T(BiTree T)
{
    /*计算树的宽度,空二叉树的宽度为0,对一颗非空的二叉树各层所包含的
     *结点个数分别进行计数,其中的最大着为此非空二叉树的宽度
     *算法思路:对树进行分层的层次遍历,每遍历完一层,比较该层宽度与前k层最大宽度的大小
     */
    int parentsize,currentsize,maxsize;
    parentsize = currentsize = maxsize = 0;
    if(T == NULL)
        return 0;
    qnode *head,*rear,*p,*q;//用来存放结点
    head = rear = NULL;
    p = (qnode*)malloc(sizeof(qnode));
    p->addr = T;
    p->link = NULL;
    head = p;//根节点入队
    rear = p;
    parentsize = maxsize= 1;
    int i;
    while(head!= NULL)
    {
        currentsize = 0;
        i = 0;
        while(i < parentsize && head != NULL)//遍历该层,获取该层宽度
        {
            if(head != NULL)
            {
                if(head->addr->leftChild != NULL)
                {
                    p = (qnode*)malloc(sizeof(qnode));
                    p->addr = head->addr->leftChild;
                    p->link = NULL;
                    rear->link = p;
                    rear = p;
                    currentsize++;
                }
                if(head->addr->rightChild != NULL)
                {
                    p = (qnode*)malloc(sizeof(qnode));
                    p->addr = head->addr->rightChild;
                    p->link = NULL;
                    rear->link = p;
                    rear = p;
                    currentsize++;
                }
            }
            q = head;
            head = head->link;
            free(q);
            i++;
        }
        if(maxsize < currentsize)
            maxsize = currentsize;
        parentsize = currentsize;
    }
    return maxsize;
}

 

你可能感兴趣的:(数据结构)