求二叉樹的深度
TimeLimit: 1000MS Memory Limit: 65536KB
SubmitStatistic
已知一顆二叉樹的中序遍歷序列和后序遍歷序列,求二叉樹的深度。
Input
輸入數據有多組,輸入T,代表有T組數據。每組數據包括兩個長度小于50的字符串,第一個字符串表示二叉樹的中序遍歷,第二個表示二叉樹的后序遍歷。
Output
輸出二叉樹的深度。
Example Input
2
dbgeafc
dgebfca
lnixu
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****************************************************/ 
新聞熱點
疑難解答