LeetCode Balanced Binary Tree

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode *root) {
        int h;
        return dfs(root, h);
    }
    
    bool dfs(TreeNode* root, int& height) {
        height = 0;
        if (root == NULL) {
            return true;
        }
        int lh, rh;
        if (!dfs(root->left, lh)) return false;
        if (!dfs(root->right, rh)) return false;
        lh++, rh++;
        int diff = lh - rh;
        if (diff < -1 || diff > 1) return false;
        if (diff < 0) {
            height =  rh;
        } else {
            height =  lh;
        }
        return true;
    }
};

 第二轮:

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.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    bool valid;
public:
    bool isBalanced(TreeNode *root) {
        valid = true;
        height(root);
        return valid;
    }
    
    int height(TreeNode* root) {
        if (!valid || root == NULL) {
            return 0;
        }
        int hl = height(root->left);
        int hr = height(root->right);
        int diff = max(hl, hr) - min(hl, hr);
        if (diff > 1) {
            valid = false;
        }
        return max(hl, hr) + 1;
    }
};

 再简化一下:

/**
 * 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) {
        return height(root) >= 0;
    }
    
    int height(TreeNode* root) {
        if (root == NULL) {
            return 0;
        }
        int lh = height(root->left);
        int rh = height(root->right);
        if (lh < 0 || rh < 0 || abs(lh - rh) > 1) {
            return -1;
        }
        return 1 + max(lh, rh);
    }
};

 

posted @ 2014-06-23 21:58  卖程序的小歪  阅读(178)  评论(0编辑  收藏  举报