题目描述 [平衡二叉树]
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解题思路
首先介绍一下什么是平衡二叉树:
平衡二叉搜索树(Self-balancing binary search tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
- 递归,如果当前节点为空,返回true;
- 否则获取当前左子树和右子树的高度并求差;
1.如果差的绝对值大于1返回false;
2.小于1则递归判断左子树和右子树是否都为平衡二叉树,是则返回true,否则false。
代码
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(!pRoot) return true;
int left_height = TreeDepth(pRoot->left);
int right_height = TreeDepth(pRoot->right);
if(abs(left_height-right_height)>1)
return false;
else
return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
}
int TreeDepth(TreeNode* pRoot){
if(!pRoot) return 0;
int res=0;
res = max(TreeDepth(pRoot->left), TreeDepth(pRoot->right)) + 1;
return res;
}
};