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. 构建二叉树
  2. 层序遍历 查找叶子节点 — 队列实现

构建二叉树

  • 二叉树构造思想和之前相同,我们使用静态链表来构造,详情见上篇文章。

层序遍历

  • 使用队列实现。队列一般实现方式为数组和链表,此处我们选择数组的方式,队列的特点是先进先出。
  • 思路:一开始将根节点push进来,看看左孩子和右孩子情况
    1)都为空,则为叶子节点,则将这个节点放入叶子节点数组中。
    2)若左孩子不为空,则将左孩子push进来
    3)若右孩子不为空,则将右孩子Push进来

代码

#include 
#include 
#define Null -1
#define MaxTree 10
#define Tree int

struct TreeNode
{
    int Data;
    Tree Left;
    Tree Right;
}T[MaxTree], queue[MaxTree];

int first = -1, last = -1;

Tree BuildTree(struct TreeNode T[]);
void Push(struct TreeNode TN);
struct TreeNode Pop();
void Travel(Tree R);

int N;


int main()
{
    Tree R;
    R = BuildTree(T);
    Travel(R);
    return 0;
}

Tree BuildTree(struct TreeNode T[])
{
	int i,Root;
	char cl,cr;
//	int i;
//	int N;
	scanf("%d",&N);
	int check[N];
	if(N)
	{
		
		for(i = 0; i < N;i++) check[i] = 0;
		for(i = 0;i < N;i++){
			T[i].Data = i;
			scanf("\n%c %c",&cl,&cr);// //把换行符放在前面吃掉前面scanf后的回车,而最后一个scanf不能有回车,一举两得
//			1. 对cl的对应处理 
			if(cl!='-'){
				// '2'-'0' = 2
				T[i].Left = cl-'0';
				check[T[i].Left] = 1;
			} 
//			Null表示为-1 
			else T[i].Left = Null;
//			2. 对cr的对应处理
 			if(cr!='-'){
				// '2'-'0' = 2
				T[i].Right = cr-'0';
				check[T[i].Right] = 1;
			} 
//			Null表示为-1 
			else T[i].Right = Null;
			
		}
		for(i = 0; i < N;i++){
			if(!check[i]) break;
		}
		Root = i;
		
	}
	return Root;
}

void Push(struct TreeNode TN)
{
    queue[++last] = TN;
}

struct TreeNode Pop()
{
    return queue[++first];
}

void Travel(Tree R)
{
	int leaves[N];
	int i,k = 0;
	struct TreeNode tmp;
	Push(T[R]);
	
	for(i = 0;i < N;i++)
	{
		tmp = Pop();
		if(tmp.Left == -1 && tmp.Right == -1){
			leaves[k++] = tmp.Data;
		}
		if(tmp.Left != -1){
			Push(T[tmp.Left]);
		}
		if(tmp.Right != -1){
			Push(T[tmp.Right]);
		}
		
	}
	
	for (i = 0; i < k-1;i++)
	{
		printf("%d ",leaves[i]);
	}
	printf("%d\n",leaves[k-1]);
}

遗忘点

++i 和i++

  • i++
x = i ++;    //先让x变成i的值1,再让i加1
  • ++i
x = ++i;    //先让i加1, 再让x变成i的值1

感想

编程小白,看到这题目,真的无从下手,但上题同构树,二叉树构建思路与这个完全一样,再就是复习了下栈和队列,继续加油~

你可能感兴趣的:(数据结构,数据结构,二叉树,队列)