Balanced Binary Tree @LeetCode

PROBLEM :

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :( O(n^2) Solution )
--------------------------------------------------------------------------------

 /*
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(root==NULL) return true ;
        int l=height(root->left) ;
        int r=height(root->right) ;
     
        if(abs(l-r)<2&&(isBalanced(root->left)&&isBalanced(root->right)))
            return true ;
        return false ;
    }
 
    int height(TreeNode* root){
        if(root==NULL)
            return 0 ;
         
        int l=height(root->left) ;
        int r=height(root->right) ;
     
        return l>r?l+1:r+1 ;
    }
};

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :( O(n) Solution )
--------------------------------------------------------------------------------

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(CheckBalenced(root)==-1)
            return false ;
        return true ;
    }
 
    int CheckBalenced(TreeNode* root){
        if(root==NULL)
            return 0 ;
         
        int l=CheckBalenced(root->left) ;
        if(l==-1)
            return -1 ;
         
        int r=CheckBalenced(root->right) ;
        if(r==-1)
            return -1 ;
         
        if(abs(l-r)>1)
            return -1 ;
         
        return l>r?l+1:r+1 ;
    }
};

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )