题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <cstddef>
#include <ios>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return bool布尔型
*/
bool IsBalanced_Solution(TreeNode* pRoot) {
// write code here
if(pRoot==nullptr){
return true;
}
int leftDep=getDep(pRoot->left);
int rightDep=getDep(pRoot->right);
int diff=leftDep-rightDep;
if(diff<-1||diff>1){
return false;
}else{
return (IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right));
}
// return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
}
int getDep(TreeNode *node){
if(node==nullptr){
return 0;
}
int leftD=getDep(node->left);
int rightD=getDep(node->right);
return leftD>rightD?leftD+1:rightD+1;
}
};
平衡二叉树,左右子树高度差不超过一。且左右子树都是平衡二叉树。 另写一个函数用于统计树高。比较左右树高度差。判断是否是高度差小于1,如果小于1 仍然需要判断是否左右子树是否是平衡二叉树
