Balanced Binary Tree - LeetCode
解法一:getDep
用于求各个点深度的,然后对每个节点的两个子树来比较深度差,时间复杂度为O(NlgN)。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int getDep(TreeNode* root)
{
if (!root) return 0;
return 1 + max(getDep(root->left), getDep(root->right));
}
bool isBalanced(TreeNode* root) {
if(!root) return true;
if(abs(getDep(root->left)-getDep(root->right)) > 1) return false;
return isBalanced(root->left) && isBalanced(root->right);
}
};
Balanced Binary Tree - LeetCode
原文:https://www.cnblogs.com/multhree/p/10586533.html