蓝桥杯:二叉树求先序遍历,已知中序,后序遍历,递归解法

蓝桥杯:二叉树求先序遍历,已知中序,后序遍历,递归解法

问题描述

给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度<=8)。
  
输入格式
  两行,每行一个字符串,分别表示中序和后序排列
输出格式
  一个字符串,表示所求先序排列

样例输入

BADC  
BDCA

样例输出

ABCD

约定

l = left 左边

r = right 右边

d = 根

ldr = 中序遍历 左中右

lrd = 后序遍历 左右中

思路

  • 后序遍历的最后一个字符是根,在中序遍历中找到根的位置 i
  • 把中序遍历结果分为 【 0 ~ i-1】 和 【 i+1 ~ 结束 】 两个子串 ldr_left 和 ldr_right
  • 求得两个子串的长度 len_left 和 len_right
  • 根据子串长度将后序遍历序列分割, 前 len_left 长度是左边子串的后序遍历 ,从 len_left下标开始到倒数第二个下标为止 是右边子串的后序遍历
  • 递归调用函数

完整代码

#include <iostream>
#include <string>

using namespace std;

void dfs(string ldr, string lrd)
{
	int len = lrd.length();
	char root = lrd[len-1];
	cout<<root;
	
	int root_index = 0;
	for(int i=0; i<len; i++)
	{
		if(ldr[i] == root)
		{
			root_index = i;
			break;
		}
	}
	
	string ldr_left = ldr.substr(0, root_index);
	string ldr_right = ldr.substr(root_index+1, len-root_index-1);
	
	int len_left = ldr_left.length();
	int len_right = ldr_right.length();
	
	string lrd_left = lrd.substr(0, len_left);
	string lrd_right = lrd.substr(len_left, len-len_left-1);
	
	if(len_left > 0)
	{
		dfs(ldr_left, lrd_left);	
	}
	if(len_right > 0)
	{
		dfs(ldr_right, lrd_right);
	}
}

int main()
{
	string ldr;
	string lrd;
	cin>>ldr;
	cin>>lrd;
	
	dfs(ldr, lrd);
	
	return 0;
}


发布了18 篇原创文章 · 获赞 0 · 访问量 127

猜你喜欢

转载自blog.csdn.net/weixin_44176696/article/details/103988849