题解 | #二叉树的直径#

二叉树的直径

https://www.nowcoder.com/practice/15f977cedc5a4ffa8f03a3433d18650d

直径就是,最大的 两个节点之间的距离。

最大的距离必然存在于某个节点的左右子树之间,这样说来,距离其实也就是左右子树的最大深度之和。所以只要在求最大深度的过程中,即后序遍历时,找到最大的左右子树深度之和就好啦。

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 int result = 0;
    public int diameterOfBinaryTree (TreeNode root) {
        
        if (root == null) {
            return 0;
        }
        depth(root);
        return result;
    }

    private int depth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = depth(root.left);
        int right = depth(root.right);
        if (left + right > result) {
            result = left + right;
        }

        return Math.max(left, right) + 1;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 11:31
点赞 评论 收藏
分享
05-29 22:11
门头沟学院 Java
Elastic90:抛开学历造假不谈,这公司的招聘需求也挺怪的,Java开发还要求你有图文识别、移动端开发和c++的经验,有点逆天了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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