题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解题思路:
这里所说的平衡二叉树不要求是搜索树,平常意义上的二叉平衡树一般都是指平衡二叉搜索树。
那么只需要判断任何一个节点的左右子树高度差是否大于1即可。
class Solution {
public:
bool isBalanTree = true;
int travalTree(TreeNode* root, int depth){
if(root == NULL){
return depth;
}
if(root->left == NULL && root->right == NULL){
return depth;
}
int lh = depth;
if(root->left != NULL){
lh = travalTree(root->left, depth+1);
}
int rh = depth;
if(root->right != NULL){
rh = travalTree(root->right, depth+1);
}
// cout<< "lh="<<lh<< " rh=" <<rh<<endl;
if((lh == depth && rh - depth > 1) || (rh == depth && lh - depth > 1) || abs(lh-rh) >1){
isBalanTree = false;
}
return max(lh, rh);
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot == NULL) return true;
travalTree(pRoot, 1);
return isBalanTree;
}
};