JZ39 平衡二叉树

本文最后更新于:2022年4月9日 中午

image-20211008111359529

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
return getDepth(pRoot) != -1;
}

int getDepth(TreeNode* root) {
if (root == nullptr) return 0;

int leftDepth = getDepth(root->left);
if (leftDepth == -1) return -1;
int rightDepth = getDepth(root->right);
if (rightDepth == -1) return -1;

return abs(leftDepth - rightDepth) > 1 ? -1 : 1 + max(leftDepth, rightDepth);
}
};