N~~

char in[10], post[10];//中序和后序遍历结果)
// 递归构建先序遍历:参数是中序和后序的范围索引
void build(int i_start, int i_end, int p_start, int p_end)
{
if (i_start > i_end) return; // 递归终止:当前子树无节点
char root = post[p_end]; // 1. 根节点(后序的最后一个节点)
printf("%c", root); // 先序遍历:先输出根
// 2. 在中序中找到根的位置,分割左、右子树
int root_idx = -1;
for (int i = i_start; i <= i_end; i++)
{
if (in[i] == root)
{
root_idx = i;
break;
}
}

// 3. 计算左子树的节点数,中序=后序
int left_len = root_idx - i_start;//中序左 根 右 左子树叶子i_start最小

// 4. 递归处理左子树:中序排列范围:[i_start, root_idx-1]
// 后序排列:[p_start, p_start+left_len-1](左子树节点数为left_len)
build(i_start, root_idx - 1, p_start, p_start + left_len - 1);

// 5. 递归右子树:中序:[root_idx+1, i_end]
//后序:[p_start+left_len, p_end-1](跳过根节点)
build(root_idx + 1, i_end, p_start + left_len, p_end - 1);
}

int main()
{
// 输入中序和后序遍历字符串
scanf("%s", in);
scanf("%s", post);

// 字符串长度(节点数)
int len = strlen(in);

// 从整棵树开始递归(中序范围0len-1,后序范围0len-1)
build(0, len - 1, 0, len - 1);

return 0;
}微信图片_2025-07-09_180441_380
微信图片_2025-07-09_180455_310
11

◮:

◮:

posted @ 2025-08-11 10:27  ervgiu28hg34y827  阅读(8)  评论(0)    收藏  举报