先序:根左右;
中序:左根右;
后续:左右根
所以通过中序确定左右子树的长度,而先序或后序确定跟;
不同的是:
先序的话数组第一个是根,而后序的话数组最后一个是根,这也就决定他们DFS的方式不同:
DFS(len_now - l, mid + l, back + l - 1);--后序
DFS(len_now - begin, mid + begin, pre + begin); --先序
后序的话,最后一个不算在左右子树里,而先序的话最头一个不算在子树里;
后序和中序还原
C++ 代码
int DFS(int len_now, int* mid, int* back)
{
int root = back[len_now];
if (len_now <= 0)return 0;
if (1 == len_now)
{
tree[++tot].val = root;
return tot;
}
int now = ++tot;
tree[now].val = root;
int l=1;
for (; l <= len_now; l++)
if (mid[l] == root)break;
tree[now].left = DFS(l - 1, mid, back);
tree[now].right = DFS(len_now - l, mid + l, back + l - 1);
return now;
}
先序和中序还原
C++ 代码
int DFS(int len_now, char* mid, char* pre)
{
char root = pre[1];
if (len_now <= 0)return 0;
if (1 == len_now)
{
tree[++tot].val = root;
return tot;
}
int now = ++tot;
tree[now].val = root;
int begin = 1;
for (; begin <= len_now; begin++)
if (root == mid[begin])break;
tree[now].left = DFS(begin - 1, mid, pre + 1);
tree[now].right = DFS(len_now - begin, mid + begin, pre + begin);
return now;
}