首页 > 代码库 > Balanced Binary Tree

Balanced Binary Tree

检测一个树是否平衡,不需要求出高度,而是从底到顶检测是否平衡,这样才算法时间复杂度为O(n)。但是需要额外的O(logn)的空间

/**
 * 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) {
        return checkBalance(root) >= 0;
    }
    int checkBalance(TreeNode *root){
         if(root == NULL) return 0;
         int left = checkBalance(root->left);
         int right = checkBalance(root->right);
         if(left < 0 || right < 0 || abs(left-right) > 1) return -1;
         return max(left,right) +1;
    }
};



Balanced Binary Tree