题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
链接
代码
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot == NULL){
return true;
}
int leftLen = TreeDepth(pRoot->left);
int rightLen = TreeDepth(pRoot->right);
if(abs(leftLen - rightLen) > 1){
return false;
}
else{
return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
}
}
int TreeDepth(TreeNode* pRoot)
{
int deep = 1;
int ans = 1;
if(pRoot == NULL){
return 0;
}
DFS(pRoot, deep, ans);
return ans;
}
void DFS(TreeNode* pRoot, int deep, int& ans){
if(pRoot->left == NULL && pRoot->right == NULL){
if(deep > ans){
ans = deep;
}
}
else{
if(pRoot->left){
DFS(pRoot->left, deep+1, ans);
}
if(pRoot->right){
DFS(pRoot->right, deep+1, ans);
}
}
}
};