二叉樹的直徑

題目描述
給定一棵二叉樹,你需要計(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;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容