LeetCode

链接

543. Diameter of Binary Tree

题意

二叉树的直径
给定一个二叉树,计算出二叉树的最大直径。
最大直径定义为:二叉树中某两个结点之间的最长路径,这个路径可能不会经过根结点。

思路

利用递归,每遍历一层时分别用两个变量记录左、右孩子结点的最长路径,通过相加更新最大值。最终得到结果。

代码

public class Solution {
    int max = 0;
    
    public int diameterOfBinaryTree(TreeNode root) {
        maxDepth(root);
        return max;
    }
    
    private int maxDepth(TreeNode root) {
        if (root == null) return 0;
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        max = Math.max(max, left + right);
        return Math.max(left, right) + 1;
    }
}
原文地址:https://www.cnblogs.com/zyoung/p/6950019.html