brute force and bottom up


  • 0
    N
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
     //Brute force 
     //O(N ^ 2)
     //O(N)
    class Solution {
    public:
    //divide & conquer
        bool isBalanced(TreeNode* root) {
            if (root == NULL) return true;
            return isBalanced(root->left) &&
                   isBalanced(root->right) &&
                   abs(height(root->left) - height(root->right)) <= 1;
        }
    
        int height(TreeNode* root) {
            if (root == NULL) return 0;
            return max(height(root->left), height(root->right)) + 1;
        }
    };
    
    
    O(N)
    O(N)
    /**
     * 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:
    //brute force: repetition calculation of depth
    // how to avoid it
    
    //1 pass depth bottom-up
    //2 use -1 to indicate unbalanced
        bool isBalanced(TreeNode* root) {
            return balance(root) != -1;
        }
    
        int balance(TreeNode* root) {
            if (root == NULL) return 0;
            int left = balance(root->left);
            int right = balance(root->right);
            if (left == -1 ||
                right == -1 ||
                abs(left - right) > 1)
                return -1;
    
            return max(left, right) + 1;
        }
    };
    

Log in to reply
 

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