class Solution {
public:
bool isBalanTree = true;
int travalTree(TreeNode* root, int depth){
if(root == NULL){
return depth;
}
if(root->left == NULL && root->right == NULL){
return depth;
}
int lh = depth;
if(root->left != NULL){
lh = travalTree(root->left, depth+1);
}
int rh = depth;
if(root->right != NULL){
rh = travalTree(root->right, depth+1);
}
// cout<< "lh="<<lh<< " rh=" <<rh<<endl;
if((lh == depth && rh - depth > 1) || (rh == depth && lh - depth > 1) || abs(lh-rh) >1){
isBalanTree = false;
}
return max(lh, rh);
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot == NULL) return true;
travalTree(pRoot, 1);
return isBalanTree;
}
};
原文:https://www.cnblogs.com/chengsheng/p/10680564.html