Share my C++ solution and idea using the TreeNode structrue


  • -1
    M

    class Solution {
    public:

    bool isBalanced(TreeNode *&root ) {
        bool right_flag ;
        bool left_flag ;
        bool this_flag ;
         if(root==NULL)
         {
            root = new TreeNode(0);
            return true;
         }
         else {
                root->val = 1;
    
                left_flag = isBalanced(root->left);
                right_flag = isBalanced(root->right);
    
                int right_val,left_val;
                right_val = root->right->val;
                left_val  = root->left->val;
    
                if(abs(left_val - right_val)>1)
                    this_flag = false;
                else this_flag = true;
    
                root->val += max(left_val,right_val);
                return this_flag&&right_flag&&left_flag;
            }
    }
    

    };

    /*The key idea is that each node in balanced binary tree its left child and right child are both balance tree meanwhile the depth difference between them is not greater than 1. */


Log in to reply
 

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