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.输出二叉树反转(指将所有非叶结点的左右孩子对换)后的层序遍历
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 ; }
相关文章推荐
- 2018天梯赛第二次训练(3)
- 2018天梯赛赛后总结
- 2018天梯赛 L2-2 小字辈
- 2018HDU多校训练-3-Problem G. Interstellar Travel
- CQUPT 2018 寒假训练 DIV2 (2)数学基础题解
- 2018 3 15省赛训练
- 2017-2018-1 20155222第二次实验
- cccc天梯赛2018~ 补题
- [置顶] 2018赛季个人训练记录
- 天梯赛训练2 5-4 最长连续递增子序列 (20分)
- 《算法竞赛-训练指南》第二章-HDU_2018
- 深度学习顶会“无冕之王”ICLR 2018评审结果出炉,斯坦福大学对抗训练研究得分第一
- PAT 2018团体程序设计天梯赛 2018我们要赢
- 2018第九届蓝桥杯-入门训练 Fibonacci数列(C语言)
- 第五周第二次训练 D题 树状数组
- 【暑期第二次训练赛】小火山的计算能力
- 2018CCCC程序设计天梯赛赛后总结
- 2018天梯赛总结
- 2018 CCCC L1 001 天梯赛座位分配
- 2018_bzu_寒假训练计划