国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

sdutacm-求二叉樹的深度

2019-11-06 06:21:49
字體:
來源:轉載
供稿:網友

求二叉樹的深度

TimeLimit: 1000MS Memory Limit: 65536KB

SubmitStatistic

PRoblem Description

已知一顆二叉樹的中序遍歷序列和后序遍歷序列,求二叉樹的深度。

Input

輸入數據有多組,輸入T,代表有T組數據。每組數據包括兩個長度小于50的字符串,第一個字符串表示二叉樹的中序遍歷,第二個表示二叉樹的后序遍歷。

Output

輸出二叉樹的深度。

Example Input

2

dbgeafc

dgebfca

lnixu

linux

Example Output

4

3

Hint

 

Author

 

#include<string.h>#include<stdio.h>#include<stdlib.h>#include<algorithm>#include<queue>#include<iostream>using namespace std;typedef struct node{   char data;   struct node*l;   struct node*r;}tree;void huifu(char *zhong,char *hou,int len)//僅僅求出后序遍歷樹{  if(len==0)  return ;  tree *p = new tree;  p->data = *(hou+len-1);  int i = 0;  for(;i<len;i++)  if(zhong[i]==*(hou+len-1))  {     break;  }   cout<<p->data;  huifu(zhong,hou,i);  huifu(zhong+i+1,hou+i,len-i-1);  return ;}tree* huifu3(char *zhong,char *hou,int len)//已知中序后序遍歷,求出并建立以該樹組成的(以后序建立的)樹;{   tree*root = new tree;   if(len==0)   return NULL;   root->data = *(hou+len-1);   int i;   for( i = 0; i < len ;i++)   {     if(zhong[i] == *(hou+len-1))     break;   }   root->l = huifu3(zhong,hou,i);   root->r = huifu3(zhong+i+1,hou+i,len-i-1);  return root;}tree* huifu2(char *xian,char *zhong,int len)//同上已知先序中序建立前序樹;{   tree*head =new tree;   if(len==0)   return NULL;   head->data = *(xian);   int i = 0;   for(;i<len;i++)   {       if(zhong[i]==*xian)       break;   }   head->l = huifu2(xian+1,zhong,i);   head->r = huifu2(xian+i+1,zhong+i+1,len-i-1);   return head;}void last(tree*root)/*后序遍歷樹*/{   if(root)   {      last(root->l);      last(root->r);      cout<<root->data;   }}int high(tree*root)//遞歸求出樹的高度{   if(!root)   return 0;   else   return max(high(root->l),high(root->r))+1;}void ccout(tree*root)//層次遍歷(從上到下,從左到右)先序樹,并打印{    queue<tree*>q;    tree*p =NULL;    if(root)    {      q.push(root);    }    while(!q.empty())    {        p = q.front();        q.pop();        cout<<p->data;        if(p->l)        {           q.push(p->l);        }        if(p->r)        {           q.push(p->r);        }    }}int main(){   char hou[102],zhong[102],xian[102];   int o;   cin>>o;   while(o--)   {    int len;   scanf("%s%s",zhong,hou);   len = strlen(zhong);   tree* root;   root = huifu3(zhong,hou,len);   int u = high(root);   cout<<u<<endl;   }}/***************************************************User name: jk160505徐紅博Result: AcceptedTake time: 0msTake Memory: 160KBSubmit time: 2017-02-07 16:12:17****************************************************/

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 科技| 珠海市| 新宁县| 天津市| 昆山市| 衡水市| 江北区| 龙南县| 志丹县| 云阳县| 南京市| 遂川县| 新郑市| 晋宁县| 土默特右旗| 西吉县| 温州市| 罗田县| 兰西县| 桃园县| 平武县| 黄山市| 昆明市| 扎兰屯市| 来安县| 武穴市| 班戈县| 房山区| 定安县| 巧家县| 娄底市| 江永县| 阳山县| 桃江县| 德江县| 双城市| 砀山县| 江陵县| 南投县| 雅安市| 得荣县|