题解 | #牛群的最长距离#
牛群的最长距离
https://www.nowcoder.com/practice/82848c6aa1f74dd1b95d71f3c35c74d5?tpId=354&tqId=10595822&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj
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整型
*/
private static Integer maxDepth = 0;
public int diameterOfBinaryTree(TreeNode root) {
search(root);
return maxDepth;
}
public int search(TreeNode root) {
if (root == null) {
return 0;
}
int left = search(root.left);
int right = search(root.right);
maxDepth = Math.max(maxDepth, left + right);
return Math.max(left, right) + 1;
}
}
本题知识点分析:
1.二叉树遍历
2.DFS深度优先搜索
3.数学模拟
本题解题思路分析:
1.本题和求高度有点类似
2.如果root=null,返回0
3.递归左子树和右子树分别获得路径
4.Math.max取最长路径
5.只要节点不为null,返回left和right中长的路径,并且+1,因为到达该结点还需+1
本题使用编程语言: Java
如果本篇文章对您有帮助的话,可以点个赞支持一下,感谢~

