Brush questions-Leetcode-interview questions 04.04. Check balance (recursive, deep search)

Interview Question 04.04. Check balance

Topic link

Source: LeetCode
Link: https://leetcode-cn.com/problems/check-balance-lcci/

Title description

Implement a function to check whether the binary tree is balanced. In this problem, the definition of a balanced tree is as follows: For any node, the height difference between its two subtrees does not exceed 1.

Example 1:
a given binary tree [3,9,20, null, null, 15,7]
. 3
/
. 9 20 is
/
15. 7
returns true.
Example 2:
given binary tree [1,2,2,3,3, null, null, 4,4 &]
. 1
/
2 2
/
. 3. 3
/
. 4. 4
returns false.

Topic analysis

Top-down recursion

/**
 * 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==NULL){
    
    
            return 0;
        }else{
    
    
            return max(height(root->left),height(root->right)) +1;
        }
    }
    bool isBalanced(TreeNode* root) {
    
    
        if(root==NULL){
    
    
            return true;
        }else{
    
    
            return abs(height(root->left)-height(root->right))<=1 && isBalanced(root->left) && isBalanced(root->right);
        }
    }
};

Guess you like

Origin blog.csdn.net/qq_42771487/article/details/112985064
Recommended