判断一棵二叉树是不是平衡二叉树
如果某二叉树中的任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
struct BinaryTreeNode { int value; BinaryTreeNode* p_left; BinaryTreeNode* p_right; }; bool IsBalanced(BinaryTreeNode* pRoot, int* pDepth) { if( pRoot == NULL) { *pDepth = 0; return true; } int left,right; if(IsBalanced(pRoot->p_left,&left) && IsBalanced(pRoot->p_right,&right)) { int diff = left - right; if( diff <= 1 && diff >= -1) { *pDepth = 1 + (left > right ? left: right); return true; } } return false; } bool IsBalanced(BinaryTreeNode* pRoot) { int depth=0; return IsBalanced(pRoot,&depth); }