题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return bool布尔型 */ int depth(struct TreeNode* pRoot){//求树的度 if(pRoot==NULL){ return 0; } if(depth(pRoot->left)>depth(pRoot->right))//返回左右子树最大的度+1 return depth(pRoot->left)+1; else return depth(pRoot->right)+1; } bool b=true; bool IsBalanced_Solution(struct TreeNode* pRoot ) { // write code here if(pRoot==NULL) return true;//如果为空树,则返回true if(depth(pRoot->left)>depth(pRoot->right)+1||depth(pRoot->left)<depth(pRoot->right)-1){//判断左右子树的度是否差一 b=false; return b; }else{ IsBalanced_Solution(pRoot->left); IsBalanced_Solution(pRoot->right); } return b; }