题目描述
已知树形结构的所有节点信息,现要求根据输入坐标(x,y)找到该节点保存的内容值,其中x表示节点所在的层数,根节点位于第0层,根节点的子节点位于第1层,依次类推;y表示节点在该层内的相对偏移,从左至右,第一个节点偏移0,第二个节点偏移1,依次类推;
![](https://i-blog.csdnimg.cn/blog_migrate/87f0f1c0e43486b5b67abda34f2782a7.png)
举例:上图中,假定圆圈内的数字表示节点保存的内容值,则根据坐标(1,1)查到的内容值是23。
输入描述
每个节点以一维数组(int[])表示,所有节点信息构成二维数组(int[][]),二维数组的0位置存放根节点;
表示单节点的一维数组中,0位置保存内容值,后续位置保存子节点在二维数组中的索引位置。
对于上图中:
根节点的可以表示为{10,1,2},
树的整体表示为{{10,1,2},{-21,3,4},{23,5},{14},{35},{66}}
查询条件以长度为2的一维数组表示,上图查询坐标为(1,1)时表示为{1,1}
使用Java标准IO键盘输入进行录入时,
先录入节点数量
然后逐行录入节点
最后录入查询的位置
对于上述示例为:
6
10 1 2
-21 3 4
23 5
14
35
66
1 1
输出描述
查询到内容时,输出{内容值},查询不到时输出{}
上图中根据坐标(1,1)查询输出{23},根据坐标(1,2)查询输出{}
用例
输入 | 6 10 1 2 -21 3 4 23 5 14 35 66 1 1 |
输出 | {23} |
说明 | 无 |
输入 | 14 0 1 2 3 4 -11 5 6 7 8 113 9 10 11 24 12 35 66 13 77 88 99 101 102 103 25 104 2 5 |
输出 | {102} |
说明 | 无 |
输入 | 14 0 1 2 3 4 -11 5 6 7 8 113 9 10 11 24 12 35 66 13 77 88 99 101 102 103 25 104 3 2 |
输出 | {} |
说明 | 无 |
输入 | 1 1000 0 0 |
输出 | {1000} |
说明 | 无 |
package com.itheima.华为机考;
import java.util.*;
/**
* @author guts
* @Date 2023/2/23 9:38
* @Version 1.0
*查找树中元素
*/
public class HW057 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
int n = Integer.parseInt(sc.nextLine());
int[][] arr=new int[n][];
for (int i = 0; i < arr.length; i++) {
arr[i]= Arrays.stream(sc.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
}
int[] nums = Arrays.stream(sc.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int row=nums[0];
int col=nums[1];
//保存每一层的节点,key是层数,value是该层所有节点,例如2,2对应的值可以map.get(2).get(2)获得
HashMap<Integer,ArrayList<Integer>> map=new HashMap<>();
//保存上一层的节点
LinkedList<Integer> preQue=new LinkedList<>();
//保存本层节点
LinkedList<Integer> curQue=new LinkedList<>();
//层数,0层的时候对preQue进行填数特殊处理了,所以从1开始,level在进行preQue和curQue新老交替时level数加1
int level=1;
for (int i = 0; i < n; i++) {
//i=0对应着第0层,填数特殊处理
if(i==0){
for (int j = 0; j < arr[i].length; j++) {
if(j==0){
map.putIfAbsent(0,new ArrayList<>());
map.get(0).add(arr[i][j]);
}else preQue.addFirst(arr[i][j]);
}
}else {
//preQue。size为0,表示这一层已经结束,进行新老交替,同时层数加一
if(preQue.size()==0){
preQue=curQue;
curQue=new LinkedList<>();
level++;
}
//preQue不是空的,就继续遍历,每次移除一个元素
if(!preQue.isEmpty()){
preQue.removeLast();
for (int j = 0; j < arr[i].length; j++) {
if(j==0){
map.putIfAbsent(level,new ArrayList<>());
map.get(level).add(arr[i][j]);
//j==0是值,后面的是要加入queue中的索引,其实有用的只是索引的个数,而不是对应值
}else curQue.addFirst(arr[i][j]);
}
}
}
}
//打印结果
ArrayList<Integer> list = map.get(row);
if(list==null) System.out.println("{}");
else {
if(col<list.size()){
System.out.println("{"+list.get(col)+"}");
}else System.out.println("{}");
}
}
}
}