0311-二叉树的直径
二叉树的直径
前几天一直没写这个,因为觉得写leetcode题解的人已经很多了,而且大多都解释得比我好多了,感觉没有必要写这个。但是咋说呢,写这些也不是为了要给谁看,只是写出来梳理一遍思路,借鉴他人的优秀代码,让自己能多少领悟到如何让代码变得优雅,自己有所提升就行了,不用太在乎其他的。
题目卡片
-
时间: 2020-03-10
-
Tag:树
-
题目描述:给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
思路
示例: 1 / \ 2 3 / \ 4 5
代码
class Solution {
int res = 0;
public int diameterOfBinaryTree(TreeNode root) {
if(root == null)
return 0;
maxDepth(root);
return res;
}
public int maxDepth(TreeNode curroot){
if(curroot == null)
return 0 ;
int LD = maxDepth(curroot.left);
int RD = maxDepth(curroot.right);
if(LD+RD>res)
res = LD+RD;
return Math.max(LD,RD)+1;
}
}
扩展



浙公网安备 33010602011771号