[LeetCode] Balanced Binary Tree

Balanced Binary Tree

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.

解题思路:

先检查左孩子树的高度与右孩子树的高度是否相差大于1。若大于1,则返回false,否则检查左孩子树和右孩子树是否均是平衡树。

/**
 * 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 leftH = TreeHeight(root->left);
        int rightH = TreeHeight(root->right);
        if(leftH > rightH + 1 || leftH < rightH -1){
            return false;
        }
        return isBalanced(root->left) && isBalanced(root->right);
    }
    
    int TreeHeight(TreeNode* root){
        if(root==NULL){
            return 0;
        }else{
            return 1+max(TreeHeight(root->left), TreeHeight(root->right));
        }
    }
    
};

二次刷题(2015-08-04)

/**
 * 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 leftHeight = getHeight(root->left);
        int rightHeight = getHeight(root->right);
        if(abs(leftHeight - rightHeight)>1){
            return false;
        }
        return isBalanced(root->left) && isBalanced(root->right);
    }
    
    int getHeight(TreeNode* root){
        if(root==NULL){
            return 0;
        }
        return 1 + max(getHeight(root->left), getHeight(root->right));
    }
};


0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注