二叉树的层次遍历 数组版
来源:互联网 发布:php字符串替换 第一个 编辑:程序博客网 时间:2024/05/29 17:21
白书 上的解法真是各种不明觉厉,只好去求教硕神,哎,差距真大,好好学习吧,任重道远
#include<stdio.h>#include<string.h>#include<stdlib.h>const int MAXN=300;struct Node{int left,right;int vis;int val;}tree[MAXN];char s[MAXN];int cnt,ans[MAXN],next,root;int newnode(){tree[next].vis=tree[next].left=tree[next].right=0;return next++;}void addnode(int val,char *s) //表示树中添加结点{int len=strlen(s);int u=0; //从根结点向下走for(int i=0;i<len;i++){if(s[i]=='L'){if(tree[u].left==0){tree[u].left=newnode();}u=tree[u].left;}else if(s[i]=='R'){if(tree[u].right==0){tree[u].right=newnode();}u=tree[u].right;}}tree[u].val=val; tree[u].vis=1;}int readin() //输入部分{next=0; //next为结点的位置root=newnode();for(;;){if(scanf("%s",s)!=1) return 0;if(!strcmp(s,"()")) break;int val;sscanf(&s[1],"%d",&val);addnode(val,strchr(s,',')+1);}return true;}int bfs() //遍历二叉树{int front=0,rear=1;int q[MAXN];q[0]=root;while(front<rear){int u=q[front++];if(!(tree[u].vis))return 0;ans[cnt++]=tree[u].val;if(tree[u].left)q[rear++]=tree[u].left;if(tree[u].right)q[rear++]=tree[u].right;}return true;}int main(){ while(readin()) { cnt = 0; if(bfs()) { for(int i = 0; i < cnt-1; i++) printf("%d ", ans[i]); printf("%d\n", ans[cnt-1]); } elseputs("-1"); }return 0;}
0 0
- 二叉树的层次遍历 数组版
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历!!!
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- UML类图符号 各种关系说明以及举例
- 腾讯、优酷视频地址解析(转)
- hdu 1796 How many integers can you find (容斥原理)
- Cython的学习方法
- 大神与三位小伙伴
- 二叉树的层次遍历 数组版
- R语言数据挖掘中常用函数
- java web学习笔记(二)---程序调试
- 飞过的人故意让他好大方的风格化大方更好的风格回个话功夫
- 于人天涯风格化德国的更好的风格的个方法的个复古
- TCP协议三次握手过程分析
- 【LeetCode】Path Sum
- 记得感激我 评论我 nvidia显卡驱动linux系统地安装 完全驱动方法 世界第一人
- 使用Http下载文件