给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过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:
int Depth(TreeNode* root)
{
if(root==nullptr)
return 0;
int leftDepth=Depth(root->left);
int rightDepth=Depth(root->right);
return leftDepth>rightDepth ? leftDepth+1:rightDepth+1;
}
bool isBalanced(TreeNode* root) {
if(root==nullptr)
return true;
int leftDepth=Depth(root->left);
int rightDepth=Depth(root->right);
//判断当前树
return abs(leftDepth-rightDepth)<2
//递归判断左子树和右子树
&&isBalanced(root->left)
&&isBalanced(root->right);
}
};