C 熟悉二叉树的构建 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

简而言之
输入:
节点数 N
N个结点,节点的左子树,右子树索引

输出:
从上到下,从左到右找寻叶节点——左右子树都为空
队列方式——逐个输出 叶的索引,最后不能有空格

解题
1.构造节点类型

struct TreeNode{
	 int left;        //左子树的索引 
	 int right;       //右子树的索引,为空则-1 
	 int value;
}T1[MaxTree]; 

2.创建由输入转为树的函数,树的节点保存在结构数组里
函数返回根节点的坐标。

int notroot[10]={0};
int GetTree(TreeNode T[]){     //返回该数的根节点索引 
	char cl,cr;
	int N;
	int Root;
	scanf("%d\n",&N);           //后面是用是scanf char类型的,所以前面的换行符也要消掉 
	for (int i=0;i<N;i++){
		scanf("%c %c\n",&cl,&cr);   
		//cin>>cl>>cr; 
		if(cl!='-'){
			T[i].left=cl-'0';
			notroot[T[i].left]=1;
		}
		else T[i].left=Null;
		if(cr!='-'){
			T[i].right=cr-'0';
			notroot[T[i].right]=1;
		}
		else T[i].right=Null;
		T[i].value=i;
	}             //所有节点放入数组 
	//找根节点
	for(int i=0;i<N;i++){
		if(!notroot[i]){
			Root=i;
			break;
		}
	} 
	return Root;      //返回根节点坐标 
}

3.主函数
包括输出,
为了不让最后输出空格,则设置标记flag,第一个数前面不输出space,而后面的数都输出space;

int main(){
	int R=GetTree(T1);       //把树存在T1里,并得到根节点索引R
	 //建队列,挨个入队,找到没有左右子树的点,输出
	queue<TreeNode> A;
	A.push(T1[R]);
	queue<int> result;
	int flag =0; 
	while(!A.empty()){
		TreeNode temp = A.front();
		A.pop();
		if(temp.left!=Null){                //从根节点开始 不为空则左右子树入队 
			A.push(T1[temp.left]);    //先左 
		} 
		if(temp.right!=Null){
			A.push(T1[temp.right]);    //后右 
		}
		
		if(temp.right==Null&&temp.left==Null){
			if(flag!=0){
				printf(" ");
			}
			flag=1;
			printf("%d",temp.value);
		}
	}
	return 0;  
}

注意点
二叉树的构建用到结构数组,并先找到根节点,即可遍历二叉树;

发布了77 篇原创文章 · 获赞 3 · 访问量 3033

猜你喜欢

转载自blog.csdn.net/BLUEsang/article/details/105301305
今日推荐