Programmer interview golden classic-interview questions 04.04. Check balance

1. Topic introduction

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:
Given a binary tree [3,9,20,null,null,15,7]
    3
   / \
  9 20
    / \
   15 7
returns true.
Example 2:
Given a binary tree [1,2,2,3,3,null,null,4,4]
      1
     / \
    2 2
   / \
  3 3
 / \
4 4
returns false.

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/check-balance-lcci The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, problem-solving ideas

       This question examines the calculation of the height of the binary tree, and requires that the height difference between the left and right subtrees of each node cannot be greater than 1.

Three, problem-solving code

class Solution {
private:
    bool flag = true;
public:
    //求二叉树的高度问题
    bool isBalanced(TreeNode* root) {
        depth(root);
        return flag;
    }


    int depth(TreeNode* root)
    {
        if(!root)
            return 0;
        int left = depth(root->left);
        int right = depth(root->right);
        if(abs(left - right) > 1)  //当左右子树的高度差大于1时,该标记就会被记录下来
            flag = false;
        return max(left, right) + 1;
    }
};

Four, problem-solving results

Guess you like

Origin blog.csdn.net/qq_39661206/article/details/108055292