平衡二叉樹
給定一個二叉樹,确定它是高度平衡的。對于這個問題,一棵高度平衡的二叉樹的定義是:一棵二叉樹中每個節點的兩個子樹的深度相差不會超過1。
先求左子樹和右子樹的最大深度,然後判斷是否相差大于1,如果是,則不可能是,如果相差小于,繼續遞歸調用判斷左子樹和右子樹是否都是平衡二叉樹。
代碼實作
bool isBalanced(TreeNode *root) {
// write your code here
if(root == NULL)
return true;
int leftDepth = MaxDepth(root->left);
int rightDepth = MaxDepth(root->right);
if(abs(rightDepth - leftDepth) > )
{
return false;
}
else{
return isBalanced(root->left) && isBalanced(root->right);
}
}
int MaxDepth(TreeNode *root){
if(root == NULL)
return false;
int leftDepth = MaxDepth(root->left) + ;
int rightDepth = MaxDepth(root->right) + ;
return leftDepth > rightDepth ? leftDepth : rightDepth;
}