根据二叉树的中序和后序还原二叉树

来源:互联网 发布:找出两列不同的数据 编辑:程序博客网 时间:2024/05/22 05:12

P:终点时要明白二叉树的几种遍历方法以及规律;

先序:中左右。

中序:左中右。

后序:左右中。

上面的左右皆为中的子树,所以优势具有二叉树的特性,那么我们就可以递归还原树了;

这里是一个二叉树还原及求深度。

/*****************************************Author      :Crazy_AC(JamesQi)Time        :2015File 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_backtemplate<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;}/*2dbgeafcdgebfcalnixulinux*/


0 0