/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ #include "math.h" //返回当前树的深度 #include <stdbool.h> #include <stdlib.h> int depth_tree(struct TreeNode* node) { if(node==NULL) return 0; int depth1=depth_tree(node->left); int depth2=depth_tree(node->right); //这里有一点抽象,可以画个简单的图理解一下,初值为0,但是对于没有子结点的结点来说:depth1与depth2都等于0,所以返回1,以此类推 int depth = depth1>depth2? depth1+1:depth2+1; return depth; } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return bool布尔型 */ bool IsBalanced_Solution(struct TreeNode* pRoot ) { // write code here if(pRoot==NULL) return true; int L=depth_tree(pRoot->left); int R=depth_tree(pRoot->right); if(abs(L-R)>1) return false; return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right); }