标签:style blog 使用 os io ar 2014 div
题目:判断一棵二叉树是否是完全二叉树代码:
bool isCompleteTree(pTree pT) { Queue q; initQueue(&q); Enqueue(&q,pT);//根入队 pNode ptr = NULL; while((ptr = Dequeue(&q)) != NULL)//不断出队,直到遇到空 { Enqueue(&q,ptr->left);//入队左孩子,空结点也同样入队 Enqueue(&q,ptr->right);//入队右孩子 } while(!isQueueEmpty(&q))//如果队列非空,那么留在队列中的必然都是NULL结点 { ptr = Dequeue(&q); if(ptr != NULL)//如果存在非null结点,说明不是完全二叉树 { return false; } } return true; }完整代码:
/* 判断是否是完全二叉树 by Rowandjj 2014/8/19 */ #include<iostream> using namespace std; typedef struct _NODE_ { int data; struct _NODE_ *left; struct _NODE_ *right; }Node,*pNode,*pTree; typedef struct _QUEUENODE_ { pNode queue_data; struct _QUEUENODE_ *next; }QueueNode,*pQueueNode; typedef struct _QUEUE_ { pQueueNode pHead; pQueueNode pTail; int size; }Queue,*pQueue; void initQueue(pQueue pQ) { pQ->pHead = pQ->pTail = (pQueueNode)malloc(sizeof(QueueNode)); if(!pQ->pTail) { exit(-1); } pQ->pHead->next = NULL; pQ->size = 0; } void Enqueue(pQueue pQ,pNode data) { if(pQ == NULL) { return; } pQueueNode pNew = (pQueueNode)malloc(sizeof(QueueNode)); if(!pNew) { exit(-1); } pNew->queue_data = data; pNew->next = NULL; pQ->pTail->next = pNew; pQ->pTail = pNew; pQ->size++; } pNode Dequeue(pQueue pQ) { if(pQ == NULL) { return NULL; } pQueueNode pDel = pQ->pHead->next; if(pDel == NULL) { return NULL; }else { pNode result = pDel->queue_data; if(pQ->pTail == pDel) { pQ->pTail = pQ->pHead; } pQ->pHead->next = pDel->next; pQ->size--; free(pDel); return result; } } bool isQueueEmpty(pQueue pQ) { return pQ->size == 0; } bool isCompleteTree(pTree pT) { Queue q; initQueue(&q); Enqueue(&q,pT); pNode ptr = NULL; while((ptr = Dequeue(&q)) != NULL) { Enqueue(&q,ptr->left); Enqueue(&q,ptr->right); } while(!isQueueEmpty(&q)) { ptr = Dequeue(&q); if(ptr != NULL) { return false; } } return true; } void createTree(pTree *pRoot) { int data; cin>>data; if(data == -1) { return; } *pRoot = (pNode)malloc(sizeof(Node)); if(*pRoot == NULL) { exit(-1); } (*pRoot)->data = data; (*pRoot)->left = NULL; (*pRoot)->right = NULL; createTree(&(*pRoot)->left); createTree(&(*pRoot)->right); } void displayTree(pTree pT) { if(pT == NULL) { return; } cout<<pT->data<<" "; if(pT->left) { displayTree(pT->left); } if(pT->right) { displayTree(pT->right); } } int main() { pTree p = NULL; createTree(&p); cout<<isCompleteTree(p)<<endl; displayTree(p); cout<<endl; return 0; }
判断一棵二叉树是否是完全二叉树,布布扣,bubuko.com
标签:style blog 使用 os io ar 2014 div
原文地址:http://blog.csdn.net/chdjj/article/details/38685773