题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
递归,其左右子树也都为平衡二叉树
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
/*
if(pRoot == NULL)
return true;
if(pRoot ->left == NULL && pRoot ->right == NULL)
return true;
*/
if(pRoot == NULL)
return true;
if(abs(SearchDepth(pRoot ->left) - SearchDepth(pRoot ->right)) > 1)
return false;
if(IsBalanced_Solution(pRoot ->left) && IsBalanced_Solution(pRoot ->right));
return true;
return false;
}
int SearchDepth(TreeNode *root)
{
if(root == NULL)
return 0;
return 1 + max(SearchDepth(root ->left), SearchDepth(root ->right));
}
};