本文主要是介绍03-树2 List Leaves (25分),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
03-树2 List Leaves (25分)Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a "-" will be put at the position. Any pair of children are separated by a space.
Output Specification:
For each test case, print in one line all the leaves' indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.
Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
4 1 5
主要思路:
1、此题不允许调用STL的队列,需要自己构造队列,循环队列和链式队列都可以,我选择的循环队列
2、层次遍历二叉树
#include <iostream> #include<vector>using namespace std;#define Max_Node 11 #define Last -1typedef struct node {int left;int right; }Node;int CreateTree(int N,vector<Node>& Tree)//建树并返回根 {char left;char right;for (int i=0; i<N; ++i){cin>>left>>right;if (left=='-'){Tree[i].left=Last;}else{Tree[i].left=left-'0';}if (right=='-'){Tree[i].right=Last;}else{Tree[i].right=right-'0';}}int flag[N];for (int i=0; i<N; ++i){flag[i]=0;}for (int i=0; i<N; ++i){if (Tree[i].left!=Last){flag[Tree[i].left]=1;}if (Tree[i].right!=Last){flag[Tree[i].right]=1;}}int sequence;for (sequence=0; sequence<N; ++sequence){if (flag[sequence]==0){break;}}return sequence; }typedef struct queue//静态队列 {int Data[Max_Node];int Front;int Rear;int num; }Queue;void Initialize_Queue(Queue* Q) {for (int i=0; i<Max_Node; ++i){Q->Data[i]=0;}Q->Front=0;Q->Rear=0;Q->num=0; }bool Push_Queue(int data,Queue* Q) {if (Q->num==Max_Node){return false;}Q->Data[Q->Rear]=data;(Q->num)++;Q->Rear=(Q->Rear+1)%Max_Node;return true; }int Pop_Queue(Queue* Q) {int data;if (Q->num>0){data=Q->Data[Q->Front];}else{return -1;}(Q->num)--;Q->Front=(Q->Front+1)%Max_Node;return data; }int main() {vector<Node> Tree(Max_Node);int N=0;cin>>N;int Root=CreateTree(N,Tree);//ProcessQueue Q;Initialize_Queue(&Q);int flag=0;Push_Queue(Root, &Q);int value,left,right;while (Q.num>0){value=Pop_Queue(&Q);left=Tree[value].left;right=Tree[value].right;if (left!=Last){Push_Queue(left,&Q);}if (right!=Last){Push_Queue(right, &Q);}if (left==Last && right==Last){if (flag==0){flag=1;cout<<value;}else{cout<<' '<<value;}}}return 0; }
这篇关于03-树2 List Leaves (25分)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!