sicily 1935. 二叉树重建

来源:互联网 发布:沐足软件 编辑:程序博客网 时间:2024/05/19 15:23

已知先序遍历和中序遍历,求广度优先遍历

从先序遍历中可以确定树的根,在中序遍历中查找,可以得到左子树和右子树,将其压入队列中,以实现广度优先序列

在同时对先序遍历的序列和后序遍历的序列进行队列操作时,可以考虑将其包装为struct类型,避免代码的编写错误


#include <iostream>#include <string>#include <queue>using namespace std;void toBFS(string preSeq,string inSeq){queue<string> preQue,inQue;string pre,in;preQue.push(preSeq);inQue.push(inSeq);while (!preQue.empty()){pre = preQue.front();in = inQue.front();preQue.pop();inQue.pop();int root = in.find(pre[0]);string inLeft,preLeft,inRight,preRight;cout << pre[0];if (root != 0){//左子树存在inLeft = in.substr(0 ,root);preLeft = pre.substr(1,inLeft.size());preQue.push(preLeft);inQue.push(inLeft);}if (root != in.size() - 1){//右子树存在inRight = in.substr(root+1,in.size() - root);preRight = pre.substr(preLeft.size()+1,pre.size() - preLeft.size() - 1);preQue.push( preRight );inQue.push( inRight );}}}int main(){int testCount;cin >> testCount;while ( testCount--){string pre,in;cin >> pre >> in;toBFS(pre,in);cout << endl;}return 0;}


0 0
原创粉丝点击