包含多組測試數據。每組測試數據一行,給出二叉樹的先序遍歷序列(至少1個結點)。
輸出二叉樹的繁茂程度。
#include<cstdio>#include<cstdlib>#include<cmath>#include<cstring>#include<string>#include<algorithm>#include<stack>#include<queue>#include<map>#include<iostream>using namespace std;typedef struct BiTNode{ char d; struct BiTNode *l; struct BiTNode *r;}*BiTree,BiTreeNode;char ch;bool flag;void CreatBiTree( BiTree &T)//創建二叉樹{ char tmp; if( flag) scanf("%c",&tmp); else { tmp = ch; flag = 1; } if( tmp == '^') T = NULL; else { T = new BiTreeNode; T->d = tmp; CreatBiTree(T->l); CreatBiTree(T->r); }}int getdepth( BiTree T)//獲取二叉樹的深度{ if( T == NULL) { //PRintf("t=null/n"); return 0; } else { //printf("tt/n"); int left = getdepth(T->l); int right = getdepth(T->r); return 1+max(left,right); }}int getwidth( BiTree T)//求二叉樹的寬度{ if( T == NULL) return 0; queue<BiTree> q; q.push(T); int maxwidth = 1; while( true) { int len = q.size(); if( len == 0) break; while( len > 0) { BiTree t = q.front(); q.pop(); len--; if( t->l != NULL) q.push( t->l); if( t->r != NULL) q.push( t->r); } if( q.size() > maxwidth) maxwidth = q.size(); } return maxwidth;}int main(){ while( ~scanf("%c",&ch)) { if( ch == '/n') continue; BiTree T = NULL; flag = 0; CreatBiTree( T); int a = getdepth( T); int b = getwidth( T); //printf("a = %d, b = %d/n",a,b); printf("%d/n",a*b); } return 0;}
新聞熱點
疑難解答