二叉树节点间的最大距离

链接
从二叉树的节点 A 出发,可以向上或者向下走,但沿途的节点只能经过一次,当到达节点 B 时,路径上的节点数叫作 A 到 B 的距离。
现在给出一棵二叉树,求整棵树上每对节点之间的最大距离。

import java.util.Scanner;

public class Main {


    private static Info solve(Node root) {
        if (root == null) {
            return new Info(null, 0, 0);
        }
        Info left = solve(root.left);
        Info right = solve(root.right);

        int deep = Math.max(left.deep, right.deep) + 1;
        int distance = left.deep + right.deep + 1;
        Info ret = new Info(root, distance, deep);

        if (ret.distance < left.distance) {
            ret.distance = left.distance;
            ret.node = left.node;
        }

        if (ret.distance < right.distance) {
            ret.distance = right.distance;
            ret.node = right.node;
        }

        return ret;
    }


    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        while (in.hasNext()) {
            int n = in.nextInt();
            Node[] nodes = new Node[n + 1];
            for (int i = 1; i <= n; ++i) {
                nodes[i] = new Node(i);
            }
            Node root = nodes[in.nextInt()];
            for (int i = 1; i <= n; ++i) {
                int fa = in.nextInt();
                nodes[fa].left = nodes[in.nextInt()];
                nodes[fa].right = nodes[in.nextInt()];
            }
            Info ret = solve(root);
            System.out.println(ret.distance);
        }
    }
}

class Info {
    Node node;
    int distance;
    int deep;

    public Info(Node node, int distance, int deep) {
        this.node = node;
        this.distance = distance;
        this.deep = deep;
    }
}

class Node {
    Node left;
    Node right;
    int val;

    public Node(int val) {
        this.val = val;
    }
}
posted @ 2021-10-13 10:48  Tianyiya  阅读(92)  评论(0)    收藏  举报