原题链接:查找二叉树(tree_a)
package dotcpp;
import java.util.*;
public class Main {
static int cnt = 0; // 当前节点的编号
static int x; // 查找的节点值
static int index; // 查找到的节点的编号
static class Node { // 节点类
int val; // 值
int l; // 左节点的编号
int r; // 右右节点的编号
public Node(int val, int l, int r) {
this.val = val;
this.l = l;
this.r = r;
}
}
static Map map = new HashMap<>(); // 存储节点
// 中序遍历查找
public static void dfs(int cur) {
if (cur == 0) return; // 如果当前节点为0,返回
Node node = map.get(cur); // 获取当前节点
dfs(node.l); // 遍历左子树
cnt++; // 更新节点编号
if (node.val == x) { // 如果当前节点为查找节点,更新查找到的节点编号
index = cnt;
return;
}
dfs(node.r); // 遍历右子树
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // 二叉树的节点个数
x = sc.nextInt(); // 查找的节点值
// 构建二叉树
for (int i = 1; i <= n; i++) {
int val = sc.nextInt();
int l = sc.nextInt();
int r = sc.nextInt();
map.put(i, new Node(val, l, r));
}
// 从根节点开始遍历
cnt = 0;
index = 0;
dfs(1);
// 输出查找到的节点编号
System.out.println(index);
}
}0.0分
1 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复