[C++] O(n)-time


  • 0
    int diameterOfBinaryTree(TreeNode* root) {
        int diam = 0;
        height(root, diam);
        return diam;
    }
    
    int height(TreeNode *node, int &diam) {
        if (!node) return -1;
        int left = height(node->left, diam);
        int right = height(node->right, diam);
        diam = max(diam, left + 2 + right);
        return 1 + max(left, right);
    }
    

Log in to reply
 

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