/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int dep;
return checkBalance(root, dep);
}
bool checkBalance(TreeNode *root, int &dep)
{
if (root == NULL)
{
dep = 0;
return true;
}
int leftDep;
int rightDep;
bool leftBalance = checkBalance(root->left, leftDep);
bool rightBalance = checkBalance(root->right, rightDep);
dep = 1 + max(leftDep, rightDep);
int diff = abs(leftDep - rightDep);
return diff <= 1 && leftBalance && rightBalance;
}
};
LeetCode-Balanced Binary Tree
最新推荐文章于 2024-09-04 20:50:47 发布