Skip to content
本页目录

题目描述

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

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

示例 : 给定二叉树

          1
         / \
        2   3
       / \     
      4   5    

返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。 注意:两结点之间的路径长度是以它们之间边的数目表示。

思路

根据提议,直径为任意两个节点的路径长度。 所以他们必然有个顶点,直径的距离就是该顶点的左边深度+右边的深度。 我们定义一个函数递归求取最长深度,然后过程中记录最长的直径最后返回(因为顶点不一定就是二叉树的根节点)

参考代码

csharp
public class Solution {

    int maxDiameter = 0;
    public int MaxHeight(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = MaxHeight(root.left);
        int right = MaxHeight(root.right);
        maxDiameter = Math.Max(left+right,maxDiameter);
        return Math.Max(left,right) + 1;
    }

    public int DiameterOfBinaryTree(TreeNode root) {
        MaxHeight(root);
        return maxDiameter;
    }
}

Released under the MIT License.