给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 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:
int max(int a,int b)
{
return a>b?a:b;
}
//使用后序遍历
int depth(TreeNode* node)
{
if(node==NULL) return 0;
int leftDepth=depth(node->left);
if(leftDepth==-1) return -1;//说明左子树已经不是平衡二叉树
int rightDepth=depth(node->right);
if(rightDepth==-1) return -1;//说明右子树已经不是平衡二叉树
return abs(leftDepth-rightDepth)>1?-1:1+max(leftDepth,rightDepth);
}
bool isBalanced(TreeNode* root) {
return depth(root)==-1?false:true;
}
};