LeetCode 543.二叉树的直径

力扣题目链接:leetcode.cn/problems/di…

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。

示例 :给定二叉树

C++ LeetCode543题解二叉树直径

返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

注意:两结点之间的路径长度是以它们之间边的数目表示。

方法一:深度优先搜索求二叉树的深度

我们只需要求出每个节点的左子树的最大深度,以及右子树的最大深度。

C++ LeetCode543题解二叉树直径

AC代码

C++

class Solution {
private:
    int ans;
    int getDeepth(TreeNode* root) {
        if (!root)
            return 0;
        int left = getDeepth(root->left);
        int right = getDeepth(root->right);
        ans = max(ans, left + right);
        return max(left, right) + 1;
    }
public:
    int diameterOfBinaryTree(TreeNode* root) {
        ans = 0;
        getDeepth(root);
        return ans;
    }
};

以上就是C++ LeetCode543题解二叉树直径的详细内容,更多关于C++ 二叉树直径的资料请关注其它相关文章!

原文地址:https://juejin.cn/post/7173680113203019784

相关文章:

  • 2021-04-13
  • 2022-01-08
  • 2021-10-31
  • 2022-02-07
  • 2022-03-01
  • 2021-06-27
  • 2021-05-01
  • 2021-06-14
猜你喜欢
  • 2021-10-10
  • 2022-12-23
  • 2022-12-23
  • 2022-01-13
  • 2021-11-24
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案