//面试题55(二):平衡二叉树//题目:输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树中//任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
#include#include"BinaryTree.h"
//====================方法1====================//迭代的从上到下,判断每个节点是否是平衡树,会导致一个节点的深度重复计算
int TreeDepth(const BinaryTreeNode* pRoot)//检测节点深度
{if (pRoot ==nullptr)return 0;int nLeft = TreeDepth(pRoot->m_pLeft);int nRight = TreeDepth(pRoot->m_pRight);return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}bool IsBalanced_Solution1(const BinaryTreeNode* pRoot)//记录
{if (pRoot ==nullptr)return true;int left = TreeDepth(pRoot->m_pLeft);int right = TreeDepth(pRoot->m_pRight);int diff = left -right;if (diff > 1 || diff < -1)return false;return IsBalanced_Solution1(pRoot->m_pLeft)&& IsBalanced_Solution1(pRoot->m_pRight);
}//====================方法2====================//从下到上检测,如果节点是平衡树,就记录其深度,每个节点被计算一次
bool Is