List Leaves【建立树,层序遍历】

给定一棵树,任务是按照自顶向下、从左到右的顺序列出所有叶子节点的索引。输入包含一棵最多10个节点的树,每个节点的左右子节点索引以空格分隔,不存在的子节点用'-'表示。

7-4 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.
在这里插入图片描述

#include<iostream>
#include<queue>
using namespace std;
#define MAX 10

struct Node
{
	int left,right;
}T[MAX];

int buildTree(struct Node T[],int n)
{
	if(n==0) return -1;
	int i,flag[n];
	for(i=0;i<n;i++)
	{
		flag[i]=0;
	}
	
	char cl,cr;
	for(i=0;i<n;i++)
	{
		cin>>cl>>cr;
		
		if(cl!='-')
		{
			T[i].left=cl-'0';
			flag[T[i].left]=1;
		}
		else T[i].left=-1;
		if(cr!='-')
		{
			T[i].right=cr-'0';
			flag[T[i].right]=1;
		}
		else T[i].right=-1;
	}
	for(int i=0;i<n;i++)
		if(flag[i]==0) return i;
}

void findLeaves(int t,queue<int>&Queue,int Leaves[],int* pj)  //层序遍历找叶子 
{
	//cout<<"层序遍历:"; 
	Queue.push(t);
	int node;
	while(Queue.size())
	{
		node=Queue.front();
		Queue.pop();
		if(T[node].left==-1&&T[node].right==-1) Leaves[(*pj)++]=node;
		if(T[node].left!=-1)
			Queue.push(T[node].left);
		if(T[node].right!=-1)
			Queue.push(T[node].right);
	}
}

int main()
{
	int n,i;
	cin>>n;
	int t;
	t=buildTree(T,n);
	//cout<<"root="<<t<<endl;
	
	int Leaves[n],j=0;
	queue<int> Queue;
	for(i=0;i<n;i++) Leaves[i]=0;
	findLeaves(t,Queue,Leaves,&j);
	//cout<<"j="<<j<<endl;
	
	int flag=0;
	for(i=0;i<j;i++)
	{
		if(flag==0) flag=1;
		else cout<<" ";
		cout<<Leaves[i];
	}
	
	return 0;
} 
### 层序遍历构造二叉 层序遍历是一种按照层次顺序访问二叉节点的方式,通常借助队列来实现。通过层序遍历来构建二叉的过程可以分为以下几个方面: #### 构建过程描述 为了从给定的数组表示法还原成实际的二叉结构,可以通过模拟层序遍历的方式来逐个创建节点并连接其子节点。具体来说,对于一个包含 `null` 的数组(用于表示缺失的节点),需要跳过这些位置而不创建对应的节点。 在 JavaScript 中,这种操作可以通过维护两个指针分别指向当前正在处理的父节点以及待分配的孩子节点索引来完成[^2]。而在 Python 实现中,则更倾向于利用队列数据结构显式管理待扩展的节点列表[^3]。 以下是基于上述原理的具体实现代码示例: #### Python 实现代码 ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def build_tree_from_level_order(level_order_list): if not level_order_list or level_order_list[0] is None: return None root = TreeNode(level_order_list[0]) queue = [root] i = 1 while i < len(level_order_list): current_node = queue.pop(0) # 左孩子 if i < len(level_order_list) and level_order_list[i] is not None: left_child = TreeNode(level_order_list[i]) current_node.left = left_child queue.append(left_child) i += 1 # 右孩子 if i < len(level_order_list) and level_order_list[i] is not None: right_child = TreeNode(level_order_list[i]) current_node.right = right_child queue.append(right_child) i += 1 return root ``` 此函数接受一个代表二叉层序排列的列表作为参数,并返回重建后的根节点对象[^4]。其中特别需要注意的是当遇到值为 `None` 的时候应正确地忽略该部分而继续向下一层发展新节点的关系建立工作。 #### Java 实现代码 同样,在Java环境下我们也能采用相似逻辑来进行此类任务: ```java import java.util.*; public class Solution { public static TreeNode constructBinaryTree(Integer[] arr){ if (arr == null || arr.length == 0 || arr[0]==null ) return null; Queue<TreeNode> q=new LinkedList<>(); TreeNode root=new TreeNode(arr[0]); q.add(root); int index=1; while(!q.isEmpty() && index<arr.length ){ TreeNode node=q.poll(); // Left child processing. if(index<arr.length && arr[index]!=null){ node.left=new TreeNode(arr[index]); q.offer(node.left); } index++; // Right child processing. if(index<arr.length && arr[index]!=null){ node.right=new TreeNode(arr[index]); q.offer(node.right); } index++; } return root; } } ``` 以上展示了如何依据指定格式化的整数型数组恢复完整的二叉实例[^5]。值得注意的一点是在判定字符串或者数值是否为空时应当采取恰当方式以免引入潜在错误风险。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值