llllmz

导航

110. 平衡二叉树c

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

int max(int i,int j){
    if(i >j)  return i;
    return j;
}

int height(struct TreeNode* root){
    if(!root) return 0;
    return max(height(root->left),height(root->right))+1;
}

bool isBalanced(struct TreeNode* root) {
    if(!root) return true;
    bool a=isBalanced(root->left);
    bool b=isBalanced(root->right);
    int x=height(root->left);
    int y=height(root->right);
    if(abs(x-y)>1) return false;
    return a&&b;
}

结果:

posted on 2024-03-05 17:29  神奇的萝卜丝  阅读(8)  评论(0)    收藏  举报