题解 | #牛群的最长距离#
牛群的最长距离
https://www.nowcoder.com/practice/82848c6aa1f74dd1b95d71f3c35c74d5?tpId=354&tqId=10595822&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D354
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
private static class Result {
int maxDistance;
int maxHeight;
Result(int maxDistance, int maxHeight) {
this.maxDistance = maxDistance;
this.maxHeight = maxHeight;
}
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
public int diameterOfBinaryTree (TreeNode root) {
// write code here
if (root == null) {
return 0;
}
Result result = findMaxDistance(root);
return result.maxDistance;
}
private static Result findMaxDistance(TreeNode root) {
if (root == null) {
return new Result(0, -1);
}
Result leftResult = findMaxDistance(root.left);
Result rightResult = findMaxDistance(root.right);
int maxDistance = Math.max(Math.max(leftResult.maxDistance,
rightResult.maxDistance),
leftResult.maxHeight + rightResult.maxHeight + 2);
int maxHeight = Math.max(leftResult.maxHeight, rightResult.maxHeight) + 1;
return new Result(maxDistance, maxHeight);
}
}
知识点:
基本的Java语法和概念。
二叉树的构建和遍历。
递归算法的应用。
解题思路:
在这个实现中,我们定义了一个Result类来存储每个节点的最大距离和高度。在findMaxDistance方法中,我们使用递归遍历树来计算每个节点的最大距离和高度。对于每个节点,我们递归地计算其左子树和右子树的最大距离和高度,并根据这些信息来更新当前节点的最大距离和高度。
最终,我们通过调用maxDistance方法来计算整棵树的最大距离。
