
解题思路:递归解决
递归结束条件:传入结点为NULL
1.求出左右子树最大深度,进行比较:
若差值大于1,则为false
2.递归左右子树,再进行比较
int getDepth(struct TreeNode* node) {
if(!node)
return 0;
int left = getDepth(node->left);
int right = getDepth(node->right);
return (left < right ? right : left)+1;
}
bool isBalanced(struct TreeNode* root){
if(!root)
return 1;
int lDepth = getDepth(root->left);
printf("%d\\n",lDepth);
int rDepth = getDepth(root->right);
printf("%d",rDepth);
return ((lDepth - rDepth) <= 1 && (lDepth - rDepth) >= -1)&& isBalanced(root->left) && isBalanced(root->right);
}
