判断二叉树是否平衡
a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
以下解法为什么时间复杂度为O(n)?
/**
* 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 cntHeight(TreeNode *root) {
if(root == NULL) return ;
int l = cntHeight(root->left);
int r = cntHeight(root->right);
if(l < || r < || abs(l-r) > ) return -; //自定义 return -1,表示不平衡的情况
else return max(l, r) + ; //*******
}
bool isBalanced(TreeNode *root) {
if(root == NULL) return true;
int l = cntHeight(root->left); //-1表示不平衡
int r = cntHeight(root->right); //-1表示不平衡
if(l < || r < || abs(l-r) > ) return false;
else return true;
}
};