问题描述:
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.
过程详见代码:
/**
* 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 left = depth(root->left);
int right = depth(root->right);
if(abs(left - right) > 1) return false;
return isBalanced(root->left) && isBalanced(root->right);
}
int depth(TreeNode* root)
{
if(root == NULL) return 0;
return max(depth(root->left) + 1,depth(root->right) + 1);
}
};