Skip to content

543. 二叉树的直径 #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Doragd opened this issue Jan 1, 2024 · 0 comments
Open

543. 二叉树的直径 #11

Doragd opened this issue Jan 1, 2024 · 0 comments

Comments

@Doragd
Copy link
Owner

Doragd commented Jan 1, 2024

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;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant