1 递归
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==NULL)
return true;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
int diff=left-right;
if(diff>1 || diff<-1)
return false;
return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
}
int TreeDepth(TreeNode* pRoot){
if(pRoot == NULL){
return 0;
}
int left = TreeDepth(pRoot->left);
int right = TreeDepth(pRoot->right);
return left>right? left+1:right+1;
}
2 后续递归遍历
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth=0;
return IsBalanced(pRoot,depth);
}
bool IsBalanced(TreeNode* pRoot,int& depth){
if(pRoot == NULL){
return true;
}
int left = 0;
int right = 0;
if(IsBalanced(pRoot->left,left)&&IsBalanced(pRoot->right,right)){
int diff=left-right;
if(diff<-1||diff>1)
return false;
depth=(left>right?left:right)+1;
return true;
}
return false;
}