题解 | #牛群的最长距离#

牛群的最长距离

https://www.nowcoder.com/practice/82848c6aa1f74dd1b95d71f3c35c74d5

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.如果root=null,返回0

3.递归左子树和右子树分别获得路径

4.Math.max取最长路径

5.只要节点不为null,返回left和right中长的路径,并且+1,因为到达该结点还需+1

本题使用编程语言: Java

全部评论

相关推荐

05-27 14:57
西北大学 golang
强大的社畜在走神:27届真不用急,可以搞点项目、竞赛再沉淀沉淀,我大二的时候还在天天打游戏呢
投递华为等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务