C++ Recursive without global variable

  • 0

    Probably less efficient, but respects single responsibility principle. Height() just calculates height (or maxDepth) and diameterOfBinaryTree() handles diameter calculation. Could be optimized using some sort memoization I think, but I think it is a clear solution.

    class Solution {
        int diameterOfBinaryTree(TreeNode* root) {
            if(root == NULL)
                return 0;
            int dl = diameterOfBinaryTree(root->left);
            int dr = diameterOfBinaryTree(root->right);
            int hl = height(root->left);
            int hr = height(root->right);
            return max(hl+hr, max(dl, dr));
        int height(TreeNode* root) {
            if(root == NULL)
                return 0;
            return 1 + max(height(root->left), height(root->right));

Log in to reply

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