[力扣 Hot100]Day40 二叉树的直径-代码

时间:2024-03-07 15:10:16
#include <cmath>
class Solution {
public:
    void acc_h(TreeNode* root,int t,int& h){
        if(!root) return;
        t++;
        if(t>h)
            h=t;
        if(root->left) acc_h(root->left,t,h);
        if(root->right) acc_h(root->right,t,h);
    }
    void calculateDepth(TreeNode* root, int& max_Depth) {
        int h=0,t=0;
        acc_h(root,t,h);
        root->val=h;
        int a=0,b=0;
        if(root->left) {
            calculateDepth(root->left,max_Depth);
            a=root->left->val;
        }
        if(root->right){
            calculateDepth(root->right,max_Depth);
            b=root->right->val;
        }        
        max_Depth=max(max_Depth,a+b);
            
    }
    int diameterOfBinaryTree(TreeNode* root) {
        int max_Depth=0;
        calculateDepth(root,max_Depth);
        return max_Depth;
    }
};