题目地址:点击打开链接
二叉树重建+层序遍历
C++代码:
#include <iostream>
#include <string>
#include <deque>
#include <cctype>
#include <stack>
#include <vector>
using namespace std;
struct TreeNode
{
char data;
TreeNode *lchild,*rchild;
};
int main()
{
int n;
while(cin>>n)
{
while(n--)
{
string s;
cin>>s;
int size=s.size();
stack<TreeNode*> st;
int i;
for(i=0;i<size;++i)
{
if(islower(s[i]))
{
TreeNode *p=new TreeNode;
p->data=s[i];
p->lchild=NULL;
p->rchild=NULL;
st.push(p);
}
else
{
TreeNode *r=st.top();
st.pop();
TreeNode *l=st.top();
st.pop();
TreeNode *p=new TreeNode;
p->data=s[i];
p->lchild=l;
p->rchild=r;
st.push(p);
}
}
deque<TreeNode*> dt;
dt.push_back(st.top());
vector<char> vc;
while (!dt.empty())
{
TreeNode *p=dt[0];
dt.pop_front();
vc.push_back(p->data);
if(p->lchild)
dt.push_back(p->lchild);
if(p->rchild)
dt.push_back(p->rchild);
}
for(i=size-1;i>=0;--i)
cout<<vc[i];
cout<<endl;
}
}
return 0;
}