7-4 List Leaves

本文介绍了一种层序遍历二叉树的方法,即从上到下、从左到右的顺序列出所有叶子节点的索引。通过使用循环队列实现层序遍历,文章详细解释了如何构建队列、判空、判满以及插入和删除操作。

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

 

#include<stdio.h>
#include<stdlib.h>

#define MAXSIZE 100

//树结点结构 
typedef struct TNode{
	int Left;  //指向左子树的指针
	int Right; 
}Tree;

//循环队列元素结构 
struct QNode {
    int *Data;     /* 存储元素的数组 */
    int Front, Rear;       /* 队列的头、尾指针 */
    int MaxSize;           /* 队列最大容量 */
};
typedef struct QNode *Queue;

void LevelOrderTraversal(Tree a[],int Root);

int main()
{
	int N;
	char u,v;
	int son[15] = {0};  //将会用来判断哪个结点是根结点 
	int root;  //二叉树的根结点 
	Tree a[15] = {-1};
	
	scanf("%d",&N);
	getchar(); //吸收掉换行符 
	for(int i=0; i<N; i++){
		scanf("%c %c",&u,&v);
		if(u == '-'){
			u = -1;  //没有儿子,指针设为-1
		}else{
			u = u-'0';
			son[u] = 1; //有指针指向的结点、在son[]数组里设为1 
		}
		if(v == '-'){
			v = -1;  //没有儿子,指针设为-1
		}else{
			v = v-'0';
			son[v] = 1;
		}
		a[i].Left = u;  //数组的下标代表了这个结点的指针 
		a[i].Right = v;
		getchar();  //吸收掉换行符 
	}
    /*寻找根结点*/ 
	for(root=0; root<N && son[root]==1; root++);   
	LevelOrderTraversal(a,root);
	
	return 0;
}

//创建空循环队列 
Queue CreateQueue( int MaxSize )
{
    Queue Q = (Queue)malloc(sizeof(struct QNode));
    Q->Data = (int *)malloc(MaxSize * sizeof(int));
    Q->Front = Q->Rear = 0;
    Q->MaxSize = MaxSize;
    return Q;
}

//判队循环队列空 
bool IsEmptyQ( Queue Q )
{
    return (Q->Front == Q->Rear);
}

//判队循环队列满 
bool IsFullQ( Queue Q )
{
    return ((Q->Rear+1)%Q->MaxSize == Q->Front);
}

//循环队列的插入 
bool AddQ( Queue Q, int X )
{
    if ( IsFullQ(Q) ) {
        printf("队列满\n");
        return false;
    }
    else {
        Q->Rear = (Q->Rear+1)%Q->MaxSize;
        Q->Data[Q->Rear] = X;
        return true;
    }
}

//循环队列的删除
int DeleteQ( Queue Q )
{
    if ( IsEmptyQ(Q) ) { 
        printf("队列空\n");
        //return;
    }else{
        Q->Front = (Q->Front+1)%Q->MaxSize;
        return  Q->Data[Q->Front];
    }
}

/********层序遍历*******/
void LevelOrderTraversal(Tree a[],int Root)
{
	Queue Q;
	int r,ans = 1;
	if( Root == -1 )  return;  //如果Root为-1,说明不存在根结点,则直接返回 
	Q = CreateQueue(MAXSIZE);  //创建并初始化队列 Q
	AddQ(Q,Root);
	while( !IsEmptyQ(Q) ){
		r = DeleteQ(Q);  
		if(a[r].Left == -1 && a[r].Right == -1){  /*访问取出队列的结点*/ 
			if(ans){
				printf("%d",r);
				ans = 0;
			}else{
				printf(" %d",r);
			}
		}
		if(a[r].Left != -1)  AddQ(Q,a[r].Left);    //访问左右儿子 
		if(a[r].Right != -1)  AddQ(Q,a[r].Right);
	}
}

 

在PTA平台上,关于List的使用有多个相关题目涉及到不同的操作。 在单链表操作方面,有从单链表 `list` 中删除第 `i` 个元素的题目。当需要对链表进行全面遍历,且要处理头节点以及后续所有节点时,会使用 `p = L` 这种方式进行遍历。例如打印链表所有节点的信息,包括头节点中可能存储的一些链表相关的元数据(如链表长度等),就需要从 `L` 开始遍历 [^1]。 还有在单链表 `list` 的第 `i` 个位置上插入元素 `x` 的题目。需要编写程序将 `n` 个整数插入初始为空的单链表,第 `i` 个整数插入在第 `i` 个位置上,这里的 `i` 代表位序,从 1 开始。插入结束后,要输出链表长度,并顺序输出链表中的每个结点的数值。并且还需尝试将最后一个整数插入到链表的第 0 个、第 `n + 2` 个位置上,以测试错误信息的输出 [^4]。 另外,有关于树的 `List` 相关题目,如 “PTA 03 - 树2 List Leaves”,要求给定一棵树,按从上到下、从左到右的顺序列出所有叶子节点 [^2]。 在链表反转方面,“PTA Reversing Linked List” 题目要求对于每个测试用例,输出反转后的有序链表,每个节点占一行,且输出格式与输入相同 [^3]。 ### 示例代码(单链表插入) ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def insert_at_position(head, i, x): new_node = ListNode(x) if i == 1: new_node.next = head return new_node current = head count = 1 while current and count < i - 1: current = current.next count += 1 if current: new_node.next = current.next current.next = new_node return head # 示例用法 head = None n = 3 values = [1, 2, 3] for i in range(1, n + 1): head = insert_at_position(head, i, values[i - 1]) current = head while current: print(current.val) current = current.next ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值