先序中序
在紙上計算一下他們轉的過程就很容易發現規律 |
寫程序更簡單,只需要計算出每個子樹的起始位置 |
計算的時候使用靜態鏈表更爲方便 |
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
using namespace std;
struct node
{
int Data;
int Right, Left;
};
vector<int> in, pre;
vector<node> T;
map<int, int> mp;
int p = -1;
int Build(int inL, int inR, int preL, int preR)
{
if (inL > inR || preL > preR)
return -1;
int data = pre[preL];
int index = mp[data];
int pos = ++p;
int l = index - inL;
T[pos].Data = data;
T[pos].Left = Build(inL, index - 1, preL + 1, preL + l);
T[pos].Right = Build(index + 1, inR, preL + l + 1, preR);
return pos;
}
void dfs(int k)
{
if (T[k].Left != -1)
{
dfs(T[k].Left);
}
if (T[k].Right != -1)
{
dfs(T[k].Right);
}
cout << T[k].Data<<' ';
}
void bfs()
{
queue<int> q;
q.push(0);
while (!q.empty())
{
int x = q.front();
cout << x << " ";
q.pop();
if (T[x].Left != -1)
q.push(T[x].Left);
if (T[x].Right != -1)
q.push(T[x].Right);
}
}
int main()
{
int N;
cin >> N;
T.resize(N);
int x;
for (int i = 0; i < N; i++)
{
cin >> x;
mp[x] = i;
in.push_back(x);
}
for (int i = 0; i < N; i++)
{
cin >> x;
pre.push_back(x);
}
Build(0, N - 1, 0, N - 1);
return 0;
}
後序中序
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
using namespace std;
struct node
{
int Data;
int Right, Left;
};
vector<int> in, post;
vector<node> T;
map<int, int> mp;
int p = -1;
int Build(int inL, int inR, int postL, int postR)
{
if (inL > inR || postL > postR)
return -1;
int data = post[postR];
int index = mp[data];
int pos = ++p;
int l = index - inL;
T[pos].Data = data;
T[pos].Left = Build(inL, index - 1, postL, postL + l - 1);
T[pos].Right = Build(index + 1, inR, postL + l, postR - 1);
return pos;
}
void dfs(int k)
{
cout << T[k].Data << ' ';
if (T[k].Left != -1)
{
dfs(T[k].Left);
}
if (T[k].Right != -1)
{
dfs(T[k].Right);
}
}
void bfs()
{
queue<int> q;
q.push(0);
while (!q.empty())
{
int x = q.front();
cout << x << " ";
q.pop();
if (T[x].Left != -1)
q.push(T[x].Left);
if (T[x].Right != -1)
q.push(T[x].Right);
}
}
int main()
{
int N;
cin >> N;
T.resize(N);
int x;
for (int i = 0; i < N; i++)
{
cin >> x;
mp[x] = i;
in.push_back(x);
}
for (int i = 0; i < N; i++)
{
cin >> x;
post.push_back(x);
}
Build(0, N - 1, 0, N - 1);
dfs(0);
return 0;
}