leetcode No110. Balanced Binary Tree

Question:

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.

判断一颗树是否是AVL,即它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

Algorithm:

判断左右高度差,递归判断左右两个子树是否是AVL

Accepted Code:

/**
 * 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 {  //左子树和右子树之差不超过1,且左右子树也是AVL
public:
    bool isBalanced(TreeNode* root) {
        if(root==NULL)return true;
        int leftDepth=0;
        int rightDepth=0;
        leftDepth=maxDepth(root->left);
        rightDepth=maxDepth(root->right);
        if(abs(leftDepth-rightDepth)>1)
            return false;
        return isBalanced(root->left)&&isBalanced(root->right);
    }
    int maxDepth(TreeNode* root) {
        int deep=0;
        if(root!=NULL)
        {
            int deep_left = maxDepth(root->left);
            int deep_right = maxDepth(root->right);
            deep = (deep_left > deep_right)?deep_left+1:deep_right+1;
        }
        return deep;
    }
};



你可能感兴趣的:(LeetCode,二叉树)