What's wrong with my c++ code?


  • 0
    W

    I got wrong answer but I just can't where the problem lies.

    public:
        int maxHeight(TreeNode* node){
            if(!node){
                return 0;
            }
            return max(maxHeight(node->left), maxHeight(node->right)) + 1;
        }
        
        int minHeight(TreeNode* node){
            if(!node){
                return 0;
            }
            return min(minHeight(node->left), minHeight(node->right)) + 1;
        }
    
        bool isBalanced(TreeNode* root) {
            if(!root){
                return true;
            }
            return (maxHeight(root) - minHeight(root) <= 1);
      
      }
    

  • 2
    B

    draw the tree you would find what is wrong

    balanced tree requires the difference between maximum height of left and maximum height of right is no more then 1 for every node. However, it is not equivalent to the difference between max height and min height.

    In addition, your isBalanced function is wrong.

    In the return statement you need to check every node by

    return isBalanced(root->left) && isBalanced(root->right) && abs(maxHeight(root->left) - maxHeight(root->right)) <= 1;

Log in to reply
 

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