数据结构:平衡二叉树(时间复杂度O(N)解法)

平衡二叉树:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1

时间复杂度O(N^2)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int TreeHeight(struct TreeNode* root)
{
    if(root == NULL)
    return 0;
    int leftheight = TreeHeight(root->left);
    int rightheight = TreeHeight(root->right);
    return leftheight > rightheight ? leftheight+1 : rightheight+1;
}

bool isBalanced(struct TreeNode* root){
    if(root == NULL)
    return true;
    int leftheight = TreeHeight(root->left);
    int rightheight = TreeHeight(root->right);
    return abs(leftheight-rightheight) < 2 &&
        isBalanced(root->left) &&isBalanced(root->right);
    }

优化:时间复杂度O(N)解法

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
typedef struct RET
{
    bool isbalanced;
    int height;
}Ret;
Ret _isBalanced(struct TreeNode* root)
{
    Ret ret;
    ret.height = 0;
    ret.isbalanced = true;
    
    if(root == NULL)
        return ret;
    Ret lret;
    lret = _isBalanced(root->left);
    if(lret.isbalanced == false)
    {
        return lret;
    }
    Ret rret;
   rret = _isBalanced(root->right);
    if(rret.isbalanced == false)
    {
        return rret;
    }
    ret.isbalanced = abs(lret.height - rret.height) < 2 ;
    ret.height = lret.height > rret.height ? lret.height+1 : rret.height+1;
    return ret;
}

bool isBalanced(struct TreeNode* root){
   Ret ret = _isBalanced(root);
    return ret.isbalanced;
    }

你可能感兴趣的:(数据结构,平衡二叉树)