首页 > 其他 > 详细

二叉树的直径

时间:2020-09-26 18:29:46      阅读:43      评论:0      收藏:0      [点我收藏+]

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。

本质上:遍历二叉树,对于任意一个节点计算其左右子树深度之和,然后寻找到一个最大值!

class Solution {

    int MaxDepths = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        depth(root);
        return MaxDepths;
    }


    private int depth(TreeNode node){
        if (node == null) return 0;
        int l = depth(node.left);
        int r = depth(node.right);
        if (l + r > MaxDepths){
            MaxDepths = l + r;
        }
        return Math.max(l,r) + 1;
    }

}

来源:https://leetcode-cn.com/problems/diameter-of-binary-tree

二叉树的直径

原文:https://www.cnblogs.com/iuyy/p/13734334.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!