根據二叉樹的中序和後序還原二叉樹
阿新 • • 發佈:2019-01-11
P:終點時要明白二叉樹的幾種遍歷方法以及規律;
先序:中左右。
中序:左中右。
後序:左右中。
上面的左右皆為中的子樹,所以優勢具有二叉樹的特性,那麼我們就可以遞迴還原樹了;
這裡是一個二叉樹還原及求深度。
/***************************************** Author :Crazy_AC(JamesQi) Time :2015 File Name : *****************************************/ // #pragma comment(linker, "/STACK:1024000000,1024000000") #include <iostream> #include <algorithm> #include <iomanip> #include <sstream> #include <string> #include <stack> #include <queue> #include <deque> #include <vector> #include <map> #include <set> #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <limits.h> using namespace std; #define MEM(a,b) memset(a,b,sizeof a) #define pk push_back template<class T> inline T Get_Max(const T&a,const T&b){return a < b?b:a;} template<class T> inline T Get_Min(const T&a,const T&b){return a < b?a:b;} typedef long long ll; typedef pair<int,int> ii; const int inf = 1 << 30; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; struct node{ char data; struct node *l,*r; }*rt; char ins[1000],postt[1000]; void Built_Bitree(node *&rt,char *in,char * post,int n){ if (n <= 0) { rt = NULL; return ; } int pos = strchr(in,post[n - 1]) - in; rt = new node; rt->data = post[n - 1]; Built_Bitree(rt->l,in,post,pos); Built_Bitree(rt->r,in + pos + 1,post + pos,n - pos - 1); return ; } int depth(node *&p){ if (!p) return 0; int ld = depth(p->l); int rd = depth(p->r); // free(p->l); // free(p->r); delete p->l; delete p->r; return Get_Max(ld + 1,rd + 1); } int main(){ // freopen("in.txt","r",stdin); // freopen("out.txt","w",stdout); int x,n,i; cin >> n; while(n--){ scanf("%s%s",ins,postt); Built_Bitree(rt,ins,postt,strlen(postt)); printf("%d\n",depth(rt)); } return 0; } /* 2 dbgeafc dgebfca lnixu linux */