/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// 递归(后序)
class Solution {
public:
int getDepth(TreeNode* root) {
if (!root) {
return 0;
}
int leftdepth = getDepth(root->left);
if (leftdepth == -1) return -1;
int rightdepth = getDepth(root->right);
if (rightdepth == -1) return -1;
int depth = 1 + max(leftdepth, rightdepth);
if (abs(leftdepth - rightdepth) > 1) return -1;
return depth;
}
bool isBalanced(TreeNode* root) {
if (getDepth(root) == -1) return false;
return true;
}
};
03-29
233
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-24
145
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)