题解 | #JZ79 平衡二叉树#
平衡二叉树
http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
//递归获取深度时进行BBT判断
class Solution {
public:
int depth(TreeNode *pRoot, bool &isBBT) {
if (!pRoot || !isBBT) return 0; //节点为空或已非BBT
int leftDepth = depth(pRoot->left, isBBT); //左子树深度
int rightDepth = depth(pRoot->right, isBBT); //右子树深度
if (abs(leftDepth-rightDepth) > 1) //若深度相差大于1,则不是BBT
isBBT = false;
return 1 + max(leftDepth, rightDepth); //子树深度+1为当前树深度
}
bool IsBalanced_Solution(TreeNode* pRoot) {
bool isBBT = true;
depth(pRoot, isBBT); //深度遍历的同时进行BBT判断
return isBBT;
}
};