One Code interview question a day 04.04. Check balance

insert image description here
Simple question
Direct recursion, get the balance of the current node through the balance and height of the subtree.
The time consumption is still relatively large, but I am too lazy to optimize it.
insert image description here

/**
 * 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 height(TreeNode* root){
    
    
        //返回节点的高
        if(!root) return 0;
        if(!root->left && !root->right) return 1;
        return max(height(root->left),height(root->right))+1;
    }
    bool isBalanced(TreeNode* root) {
    
    
        //平衡检测
        if(!root) return true;
        return (isBalanced(root->left) && isBalanced(root->right) && abs(height(root->left)-height(root->right)) <= 1);             //左子树平衡,右子树平衡并且高度差不超过1
    }
};

Guess you like

Origin blog.csdn.net/qq_41746268/article/details/108201748