借鉴一个Java版本的题解,如果已经不平衡则返回-1,否则返回高度;检查最后的结果是否为-1即可。
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
return get_depth(pRoot) != -1;
}
int get_depth(TreeNode* root)
{
if(!root) return 0;
int left = get_depth(root->left);
if(left == -1) return -1;
int right = get_depth(root->right);
if(right == -1) return -1;
return abs(left-right) > 1 ? -1 : 1 + max(left,right);
}
};
京公网安备 11010502036488号