@snuffles
2019-04-02T05:43:27.000000Z
字数 682
阅读 906
树
给定一个二叉树,判断它是否是高度平衡的二叉树。
解1:递归算树的深度return 1+max(left,right)
bool isBalanced(TreeNode* root) {
if(checkDepth(root) == -1) return false;
else return true;
}
int checkDepth(TreeNode * root){
if(root == NULL) return 0;
int left = checkDepth(root->left);
if (left == -1) return -1;
int right = checkDepth(root->right);
if (right == -1) return -1;
if(abs(right-left)>1) return -1;
else return 1+max(left,right);
}
// 解法2:
bool isBalanced(TreeNode* root) {
if(root == NULL) return true;
if (abs(getDepth(root->left)-getDepth(root->right)) >1) return false;
else{
if(isBalanced(root->left) && isBalanced(root->right)) return true;
else return false;
}
}
int getDepth(TreeNode * root){
if(root == NULL) return 0;
return 1+max(getDepth(root->left),getDepth(root->right));
}