欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode - 543. 二叉树的直径

程序员文章站 2022-05-20 10:57:14
...

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

示例 :
给定二叉树
leetcode - 543. 二叉树的直径
解题思路:使用递归,注意递归和迭代的区别

class Solution {
private:
    int sum = 0;
public:
    int depth(TreeNode* root)
    {
        if(root == NULL)
            return 0;
        int L = depth(root->left);  # 递归假定当前左子树的长度已经获得
        int R = depth(root->right);  # 递归假定当前右子树的长度已经获得
        sum = max(sum,L+R);  # 计算以当前节点为根节点事最长长度的直径
        return max(L,R)+1;
    }
    int diameterOfBinaryTree(TreeNode* root) {
        depth(root);
        return sum;
    }
};