二叉树的序遍历
来源:互联网 发布:淘宝金牌店铺联盟 编辑:程序博客网 时间:2024/06/05 06:07
二叉树的序遍历
http://codevs.cn/problem/3143/ 二叉树的序遍历.模板题
#include<iostream>#include<cstring>#include<cstdio>using namespace std;const int maxn = 1010;struct point{ int l,r;}p[maxn];void build(int l,int r,int x){ p[x]=(point){l,r};}void first(int s)//根->左->右 { if(!s) return; printf("%d ",s); first(p[s].l); first(p[s].r);}void mid(int s)//左->根->右 { if(!s) return; mid(p[s].l); printf("%d ",s); mid(p[s].r);}void nxt(int s)//左->右->根 { if(!s) return; nxt(p[s].l); nxt(p[s].r); printf("%d ",s);}int main(){ int n,a,b; scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d%d",&a,&b); build(a,b,i); } first(1);puts(""); mid(1);puts(""); nxt(1); return 0;}
http://codevs.cn/problem/2010/已知前序·中序遍历,求后序遍历
利用好前序遍历与中序遍历的性质,DFS求解
#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>#include<cmath>using namespace std;char first[10010],mid[10010];void solve(int k,int l,int r){ if(l==r) return; int pos=l; for(int i=l;i<=r;i++)//前序遍历的每一个树/子树的第一个点为根节点,从中序遍历中标记相应位置 { //中序遍历中(以下皆为中序遍历顺序)在这之前的点集为左子树范围,之后为右子树范围 if(mid[i]==first[k]) { pos=i; break; } } solve(k+1,l,pos);//k+1:下一左子树第一个节点的顺序位置 solve(k+pos-l+1,pos+1,r);//k+pos-l+1:下一右子树第一个节点的位置(根节点位置),k+pos-l为左子树最后一个节点的位置 printf("%c",first[k]);//后序遍历输出 }int main(){ scanf("%s%s",&first,&mid); solve(0,0,strlen(first)); return 0;}
阅读全文
2 0
- 二叉树的序遍历
- 二叉树的序遍历
- 二叉树的序遍历
- 二叉树的序遍历
- 二叉树的序遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 【C语言】【unix c】线程同步,条件变量,mutex锁,信号量
- 点到三角形/直线/线段的距离
- 微信小程序 —— 自定义长圆形view
- sizeof PK strlen
- 正则表达式语法入门
- 二叉树的序遍历
- [转]矩阵奇异值分解(SVD)及其应用
- python 利用正则实现简易计算器
- Oracle笔记十二:集合、序列
- 冒泡排序
- VueJs探索之watch用法详解
- CodeForces 867E Buy Low Sell High
- Struts2之HelloWolrd
- 统计单词(包括中文)出现的次数