思路:
这里采用后序遍历进行递归。如果返回-1,表示当前节点的左右子树不平衡,否则返回当前节点的最大深度。
int backSearch(TreeNode *root) {
if(nullptr == root)
return 0;
int left = backSearch(root->left);
if(left == -1) return -1;
int right = backSearch(root->right);
if(right == -1) return -1;
if(abs(left - right) > 1)
return -1;
return max(left, right) + 1;
}
bool isBalanced(TreeNode* root) {
int ret = backSearch(root);
return ret == -1 ? false : true;
}