兰聪


私信TA

用户名:dotcpp0606174

访问量:914

签 名:

等  级
排  名 2827
经  验 2060
参赛次数 0
文章发表 13
年  龄 0
在职情况 学生
学  校 鄂州职业大学
专  业

  自我简介:

TA的其他文章


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 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区