题解 | #牛群的最长距离#
牛群的最长距离
https://www.nowcoder.com/practice/82848c6aa1f74dd1b95d71f3c35c74d5
知识点:递归
思路:和上一题类似,算是最小公共祖先的简化版,
求深度的时候,是拿到左右子树的返回值,进行比较,这里只需要累加就行了
编程语言:java
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 {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
public static int sum =0;
public int diameterOfBinaryTree (TreeNode root) {
// write code here
diameter(root);
return sum;
}
private int diameter(TreeNode root) {
if (root == null) {
return 0;
}
int left = diameter(root.left);
int right = diameter(root.right);
sum = Math.max(sum, left + right);
return Math.max(left, right) + 1;
}
}
查看23道真题和解析