求树宽
与非递归求树高相同,只不过是将high++变成了最大值的判断
#include <stdio.h> #include <stdlib.h> #define MaxSize 100 typedef struct node{ int data; struct node *lchild,*rchild; }TreeNode,*Tree; typedef struct{ TreeNode* data[MaxSize]; int front; int rear; }Queue; void InitQueue(Queue &Q) { Q.front=Q.rear=0; } bool isEmpty(Queue Q) { if(Q.front==Q.rear) { return true; } else { return false; } } bool isFull(Queue Q) { if((Q.rear+1)%MaxSize==Q.front) { return true; } else { return false; } } bool EnQueue(Queue &Q,TreeNode* p) { if(isFull(Q)) { return false; } Q.data[Q.rear]=p; Q.rear=(Q.rear+1)%MaxSize; return true; } bool DeQueue(Queue &Q,TreeNode* &p) { if(isEmpty(Q)) { return false; } p=Q.data[Q.front]; Q.front=(Q.front+1)%MaxSize; return true; } void CreateTree(Tree &T) { int x; scanf("%d",&x); if(x==-1) { T=NULL; return; } else { T=(TreeNode*)malloc(sizeof(TreeNode)); T->data=x; printf("输入%d的左结点:",x); CreateTree(T->lchild); printf("输入%d的右结点:",x); CreateTree(T->rchild); } } int Wide(Tree T) { if(T==NULL) return 0; Queue Q; InitQueue(Q); TreeNode *p=T; int wide=1; int current=1; int previous=1; EnQueue(Q,p); while(!isEmpty(Q)) { DeQueue(Q,p); previous--; current--; if(p->lchild) { EnQueue(Q,p->lchild); current++; } if(p->rchild) { EnQueue(Q,p->rchild); current++; } if(previous==0) { previous=current; if(previous>wide) wide=previous; } } return wide; } int main() { Tree T; CreateTree(T); printf("%d ",Wide(T)); return 0; }
标签:144,TreeNode,14,int,Queue,front,return,rear From: https://www.cnblogs.com/simpleset/p/17763124.html