华为OD题目: 查找树中元素
输入描述:
每个节点以一维数组(into) 表示,所有节点信息构成二维数组(int),二维数组的位置存放根节点表示单节点的一维数组中,0位置保存内容值,
后续位置保存子节点在二维数组中的索引位置:对于上图中,根节点的可以表示为[10,1,2》,
树的整体表示为10,121 1-21.3 41123,51 (14113516611查询条件以长度为2的一维数组表示,
上图查询坐标为(1,1)时表示为1,11使用Java标准I0键盘输入进行录入时,先录入节点数量,然后逐行录入节点,最后录入查询的位置,
对于上述示例为:
6
10 1 2
-21 3 4
23 5
14
35
66
1 1
{23}
输出描述:
查询到内容值时,输出内容值》,查询不到时输出0
上图中根据坐标(1,1)查询输出23],根据坐标(1,2查询输出0补充说明:
考试者不需要自己编写解析输入文本的代码,请直接使用上述代码中的Parser类解析输入文本
解题思路:
- BFS 树的层序遍历 (套路一定要记住)
输入:
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}
输入:
1
1000
0 0
输出:
{1000}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = Integer.parseInt(in.nextLine());
int[][] nodes = new int[size][];
for (int i = 0; i < size; i++) {
nodes[i] = parseOneLine(in.nextLine());
}
int[] xy = parseOneLine(in.nextLine());
String result = doQuery(nodes, xy[0], xy[1]);
System.out.println(result);
}
private static int[] parseOneLine(String text) {
ByteArrayInputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
Scanner in = new Scanner(stream);
List<Integer> list = new ArrayList<>();
while (in.hasNext()) {
list.add(in.nextInt());
}
return list.stream().mapToInt(it -> it).toArray();
}
public static String doQuery(int[][] nodes, int x, int y) {
if (x < 0 || y < 0) {
return "{}";
}
return bfs(nodes, x, y);
// Please enter you code to implement this function
// return "{}";
}
public static String bfs(int[][] nodes, int x, int y) {
//根节点
int[] arr = nodes[0];
Queue<int[]> queue = new ArrayDeque<>();
queue.add(arr);
int level = 0;
while (!queue.isEmpty()) {
int n = queue.size();
//获取当前层各个节点
for (int i = 0; i < n; i++) {
int[] currNodeArr = queue.poll();
int currVal = currNodeArr[0];
//处理节点的子节点
for (int j = 1; j < currNodeArr.length; j++) {
//rowIndex 子节点对应行的索引下标
int rowIndex = currNodeArr[j];
queue.add(nodes[rowIndex]);
}
if (level == x && y == i) {
return "{" + currVal + "}";
}
}
//走到这里,说明在在x层找不到y
if (level == x) {
return "{}";
}
//遍历完当前层,后level+1
level++;
}
return "{}";
}
}