1. 程式人生 > 實用技巧 >Binary Tree Traversals HDU - 1710(二叉樹已知前序中序求後序)

Binary Tree Traversals HDU - 1710(二叉樹已知前序中序求後序)

我們知道二叉樹是指最多有兩個孩子的樹,分別為左孩子和右孩子,或者左子樹和右子樹。根據根節點以及左右子樹的訪問順序不同,對二叉樹的遍歷分別有先序遍歷、中序遍歷和後序遍歷。

現在給定一棵樹的先序遍歷和中序遍歷,試求出其後序遍歷。


#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstring>
#include<stdio.h>
#include<algorithm>
#include<map>
#include<queue>
#include<set
> #include <sstream> #include<vector> #include<cmath> using namespace std; #define ll long long int a[1000009] = {}; int b[1000009] = {}; int c[1000009] = {}; int step = 1; void buil(int L1,int R1,int L2,int R2)//a中,b前 { if (L1 > R1||L2>R2) return; int p = L1; while
(a[p] != b[L2])//找到當前的根節點 p++; buil(L1, p - 1, L2 + 1, L2 + p-L1);//遍歷左子樹 buil(p + 1, R1, L2 +p-L1+1, R2);//遍歷右子樹 c[step]= b[L2];//遞迴記錄 step++; } int main() { int n; while (~scanf("%d", &n)) { step = 1; memset(a, 0, sizeof(a)); memset(b, 0, sizeof
(b)); memset(c, 0, sizeof(c)); for (int i = 0; i < n; i++) { cin >> b[i]; } for (int i = 0; i < n; i++) { cin >> a[i]; } buil(0, n - 1, 0, n - 1); for (int i = 1; i < step; i++) { if (i == 1) cout << c[i]; else cout << " " << c[i]; } cout << endl; } }