An intuitive and primal C++ solution


  • 0
    R

    class Solution {
    public:
    int diameterOfBinaryTree(TreeNode* root)
    {

        int max=0;
        if(!root) return 0;
        int useless=largestPath(root,max);
        return max-1;
    }
    

    private:
    int largestPath(TreeNode*root,int &max)
    {
    if(root==NULL) return NULL;
    int l_largest=largestPath(root->left,max);
    int r_largest=largestPath(root->right,max);
    int sum=l_largest+r_largest+1;
    max=sum>max?sum:max;
    int tmp_max=l_largest>r_largest?l_largest:r_largest;
    tmp_max++;
    return tmp_max;
    }
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.