Doragd / Algorithm

基于GitHub Action和GitHub Issue功能记录LeetCode刷题记录

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

543. 二叉树的直径

Doragd opened this issue · comments

543. 二叉树的直径

  • 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。**注意:**两结点之间的路径长度是以它们之间边的数目表示。
class Solution {
public:
    int res = INT_MIN;
    int dfs(TreeNode *root){
        if(!root) return 0;
        int left_val = dfs(root->left);
        int right_val = dfs(root->right);
        int cur = left_val + right_val; //以当前结点为最高点的路径长度: 边的数目
        res = max(res, cur); //最大值
        return max(left_val, right_val) + 1; //单边的最大路径和: 点的数目
    }
    int diameterOfBinaryTree(TreeNode* root) {
        dfs(root);
        return res;
    }
};