原题链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/
1、后序遍历 + 剪枝
bool isBalanced(TreeNode* root) {
return dfs(root) != -1;
}
int dfs(TreeNode* root) {
if (root == NULL) return 0;
int depthLeft = dfs(root->left);
if (depthLeft == -1) return -1;
int depthRight = dfs(root->right);
if (depthRight == -1) return -1;
return abs(depthLeft - depthRight) < 2 ? max(depthLeft, depthRight) + 1 : -1 ;
}
2、先序遍历 + 判断深度
bool isBalanced(TreeNode* root) {
if(root == NULL) return true;
return abs(depth(root->right) - depth(root->left)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
int depth(TreeNode* root) {
if (root == NULL) return 0;
return max(depth(root->left), depth(root->right)) + 1;
}