题目:输入一棵二叉树的根结点,判断该树是不是平衡二叉树。
思路:我们知道,若二叉树中任意某结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。这可以用递归实现,在遍历二叉树各节点事,若节点的左右子树的深度之差不超过1,则是平衡二叉树。
struct BinaryTreeNode {
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
}
int getDepth(BinaryTreeNode *root){
if(root == NULL)
return 0;
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
return leftDepth > rightDepth?leftDepth + 1:rightDepth + 1;
}
bool isBalanceBinaryTree(BinaryTreeNode *root){
if(root == NULL)
return true;
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
int diff = leftDepth - rightDepth;
if(abs(diff) > 1)
return false;
return isBalanceBinaryTree(root->left) && isBalanceBinaryTree(root->right);
}