您的位置:首页 > 其它

2018天梯赛第二次训练(2)

2018-03-14 16:19 453 查看
二叉树的构建
1.给出一个二叉树的中序遍历和先序遍历。求它的后序遍历,并构建二叉树。tree* PreInToPost(string pre,string in){ //根据先序中序构建二叉树
if(pre.length()==0||in.length()==0){
return NULL;
}
tree* t = new tree;
t->data=pre[0];
int index=in.find(pre[0]);
t->left=PreInToPost(pre.substr(1,index),in.substr(0,index));
t->right=PreInToPost(pre.substr(index+1),in.substr(index+1));
visit(t);
return t;
}2.给出一棵二叉树的中序与后序排列。求出它的先序排列,并构建二叉树。tree* InPostToPre(string in,string post){ //根据中序后序构建二叉树
if(post.length()==0||in.length()==0){
return NULL;
}
tree* t = new tree;
t->data=post[post.length()-1];
int index=in.find(post[post.length()-1]);
t->left=InPostToPre(in.substr(0,index),post.substr(0,index));
t->right=InPostToPre(in.substr(index+1),post.substr(index,post.length()-index-1));
return t;
}
3.给出一棵二叉树的先序与后序排列。求出中序排列的数目。int PrePostToIn(string pre,string post){ //根据先序后序求中序的数目
int ans=1;
for(int i=0;i<pre.length()-1;i++){
if(post[post.find(pre[i])-1]==pre[i+1])ans<<=1;
}
return ans;
} 4.输出二叉树反转(指将所有非叶结点的左右孩子对换)后的层序遍历
void reLevelOrderTraverse(tree *t)   //反转后的层序遍历算法
{
queue<tree*>q;
q.push(t);
while(!q.empty()){
tree* t = q.front();
q.pop();
visit(t);
if(t->right)q.push(t->right);
if(t->left)q.push(t->left);
}
return ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: