/**
* 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.