题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return bool布尔型
*/
int getDeepth(struct TreeNode* root) {
if (root == NULL)
return 0;
int depth;
int rdepth = getDeepth(root->right);
int ldepth = getDeepth(root->left);
depth = ldepth > rdepth ? ldepth + 1 : rdepth + 1;
return depth;
}
bool IsBalanced_Solution(struct TreeNode* pRoot ) {
// write code here
if (pRoot == NULL)
return true;
int leftdepth = getDeepth(pRoot->left);
int rightdepth = getDeepth(pRoot->right);
int diff = leftdepth - rightdepth;
if (abs(diff) > 1) {
return 0;
}
//递归判断每个结点
return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
}
海康威视公司福利 1219人发布
查看26道真题和解析