华为OD机试题回顾
华为OD 机试题(Java实现)
小镇做题家,做题记录,微信:yatesKumi
已知树形结构的所有节点信息,现要求根据输入坐标(x,y)找到该节点保存的内容值,其中x表示节点所在的层数,
根节点位于第0层,根节点的子节点位于第1层,依此类推,
y表示节点在该层内的相对偏移,从左至右,第一个节点偏移0,第二个节点偏移1,依此类推,
举例:上图中,假定圆圈内的数字表示节点保存的内容值,则根据坐标(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
输出
{23}
举例:上图中,假定圆圈内的数字表示节点保存的内容值,则根据坐标(1,1)查到的内容值是23。
输出描述:
查询到内容时,输出{内容值},查询不到时输出{}
上图中根据坐标(1,1)查询输出{23},根据坐标(1,2)查询输出{}
示例1 输入输出示例仅供调试,后台判题数据一般不包含示例
输入
6
10 1 2
-21 3 4
23 5
14
35
66
1 1
输出
{23}
import java.util.Scanner;
public class Main {
static int[][] tree;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
tree = new int[n][n];
for (int i = 0; i < n; i++) {
tree[i][0] = sc.nextInt(); // 节点值
for (int j = 1; j <= n; j++) {
tree[i][j] = sc.nextInt(); // 子节点在数组中的索引位置
}
}
int[] pos = new int[2];
pos[0] = sc.nextInt();
pos[1] = sc.nextInt();
int res = dfs(0, pos[0], pos[1]);
if (res != -1) {
System.out.println("{" + tree[res][0] + "}");
} else {
System.out.println("{}");
}
}
public static int dfs(int cur, int x, int y) {
if (x == 0) {
return cur;
}
int[] child = tree[cur];
for (int i = 1; i < child.length; i++) {
if (child[i] != 0) { // 存在子节点
int w = width(child[i - 1]);
if (y <= w) {
return dfs(child[i - 1], x - 1, y);
} else {
y = y - w;
}
} else {
break;
}
}
return -1;
}
public static int width(int pos) { // 计算宽度
int w = 0;
while (pos != 0) {
pos = tree[pos][1];
w++;
}
return w;
}
}