I don't think this code is right but the system accepted it.


  • 0
    F
    class Solution {   
    public:   
         bool isBalanced(TreeNode *root) {   
             // Note: The Solution object is instantiated only once and is reused by each test case.   
             int depth = 0;   
             return isbalance(root, depth);    
         }   
         bool isbalance(TreeNode *root, int &depth)   
         {   
             if(root == NULL)   
             {   
                 depth = 0;   
                 return true;   
             }   
             int ld,rd;   
           if( isbalance(root->left,ld) && isbalance(root->right,rd)) 
             {   
                 if( abs(ld - rd) > 1)   
                 {   
                     return false;   
                 }   
                 depth = ld > rd ? ld + 1 : rd + 1;   
                 return true;   
             }   
         }   
    };
    

    Sorry for my pool English.
    The function isbalance() may not have return value. I don't think it's allowed. But the system accept this code. Is it a default value for this function?
    Thx a lot!


  • 0
    F

    &depth is the reference in C++, it records the current depth of subtree

    bool isbalance(TreeNode *root, int &depth)
    {
    if(root == NULL)
    {
    depth = 0;
    return true;
    }
    int ld,rd;
    if( isbalance(root->left,ld) && isbalance(root->right,rd))
    {
    if( abs(ld - rd) > 1)
    {
    return false;
    }
    depth = ld > rd ? ld + 1 : rd + 1;
    return true;
    }
    }


  • 0
    F

    I agree what you said. But
    if( isbalance(root->left,ld) && isbalance(root->right,rd))
    this line has a judge, and if it's not true,the function bool isbalance() don't have a return value (true or false). And I don't think it's true.


  • 0
    F

    Yes, it is based on an fact, the tree is balanced when all of it's subtrees are balanced ,not vice verse.


  • 0
    F

    IF a tree like[1;2,3;4,#,5,6;7,#,#,#,#,#,8,#](# means NULL)
    I used this code to run by myself, notice that at the node 2 it returns false and depth is not defined, the node 3 it returns true and the depth is 3. So I think node 1 should return uncertain value.
    But in Visual Studio 2013 I noticed that when the computer doesn't know what to be returned, it will automatically return the value false.


  • 0
    F

    "Visual Studio 2013 I noticed that when the computer doesn't know what to be returned, it will automatically return the value false." -- probably that is the default behavior of that compiler


Log in to reply
 

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