// 最大直径不一定经过root
int maxVal;
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) return 0;
getNodeCountonDiameter(root);
return maxVal - 1;
}
// 返回直径上的总节点个数
public int getNodeCountonDiameter(TreeNode root) {
if (root == null) return 0;
int left = getNodeCountonDiameter(root.left);
int right = getNodeCountonDiameter(root.right);
maxVal = Math.max(left + right + 1, maxVal);
return Math.max(left, right) + 1;
}
543. 二叉树的直径
最新推荐文章于 2022-05-10 16:13:13 发布