題目描述:
給定一棵二叉樹,你需要計(jì)算它的直徑長度。一棵二叉樹的直徑長度是任意兩個(gè)結(jié)點(diǎn)路徑長度中的最大值。這條路徑可能穿過也可能不穿過根結(jié)點(diǎn)。
示例:
給定二叉樹
1
/ \
2 3
/ \
4 5
返回 3, 它的長度是路徑 [4,2,1,3] 或者 [5,2,1,3]。
作者:tuo-jiang-de-ye-ma-2
鏈接:https://leetcode-cn.com/problems/diameter-of-binary-tree/solution/cu-su-yi-dong-kan-zhu-jie-zhi-xing-yong-shi-0-ms-z/
來源:力扣(LeetCode)
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
Java代碼:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int res = 0;
public int diameterOfBinaryTree(TreeNode root) {
if(root == null) return 0;
getMaxDep(root);
return res;
}
private int getMaxDep(TreeNode curRoot) {
if(curRoot == null) return 0;
int leftDep = getMaxDep(curRoot.left);
int rightDep = getMaxDep(curRoot.right);
if(leftDep + rightDep > res) res = leftDep + rightDep;
return Math.max(leftDep, rightDep) + 1;
}
}