03-树2 List Leaves (25分)
来源:互联网 发布:ubuntu anaconda 编辑:程序博客网 时间:2024/05/17 04:41
层序遍历
题意:
找到叶子节点 从上到下 从左到右 输出叶子节点
思路:
用一个队列来模拟
坑点:
最后输出格式要注意 最后一个没有空格
#include<cstdio>#include<queue>using namespace std;#define MaxTree 10#define ElementType char#define Tree int#define Null -1queue<int> q;struct TreeNode{ ElementType Element; Tree Left; Tree Right;}T1[MaxTree];Tree BuildTree(struct TreeNode T[]){ Tree Root = -1; int N; int check[10]; char cl,cr; scanf("%d\n", &N); //printf("N=%d\n", N); int i = 0; if(N){ for(i = 0; i < N; ++i) check[i] = 0; for(i = 0; i < N; ++i){ scanf("%c %c\n", &cl, &cr); T[i].Element = i; if(cl != '-'){ T[i].Left = cl - '0'; check[T[i].Left] = 1; }else{ T[i].Left = Null; } if(cr != '-'){ T[i].Right = cr - '0'; check[T[i].Right] = 1; }else{ T[i].Right = Null; } } for(i = 0 ; i < N; ++i){ if(!check[i]) break; } Root = i; } //printf("Root=%d\n", Root); //for(i = 0; i < N; ++i) // printf("element=%d left=%d right=%d\n", T1[i].Element, T1[i].Left, T1[i].Right); return Root;}void findLeaf(Tree R){ int flag = 1; if(R == Null) return ; q.push(R); int temp = 0; while(!q.empty()){ //printf("no empty\n"); temp = q.front(); if((T1[temp].Left == Null) && (T1[temp].Right == Null)){ if(flag){ printf("%d", temp); flag = 0; } else printf(" %d", temp); } if(T1[temp].Left != Null) q.push(T1[temp].Left); if(T1[temp].Right != Null) q.push(T1[temp].Right); q.pop(); }}int main(){ Tree R1; R1 = BuildTree(T1); findLeaf(R1); return 0;}
0 0
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- PAT - 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分) (查找叶子节点)
- [pta]03-树2 List Leaves (25分)
- UICollectionView 受 NavigationBarHidden 影响
- SQL语法【一】
- 第五周 c语言项目2 三数最大值
- js面试
- java反射
- 03-树2 List Leaves (25分)
- Android服务之PackageManagerService启动源码分析
- DialogFragment去除默认标题栏并横向充满屏幕
- java 生成二维码
- #320 – StackPanel默认如何设置子控件的大小(Default Size of StackPanel Child Controls)
- 在MyEclipse或eclipse中如何查找Tomcat的安装路径
- 最全面的前端学习资源汇总,拿走不谢!
- 关于scanf与printf里的%*d
- C语言计算文件的md5值