Bootstrap

(leetcode学习)110. 平衡二叉树

给定一个二叉树,判断它是否是

平衡二叉树

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:true

示例 2:

输入:root = [1,2,2,3,3,null,null,4,4]
输出:false

示例 3:

输入:root = []
输出:true

提示:

  • 树中的节点数在范围 [0, 5000]
  • -104 <= Node.val <= 104

很久没写结构体了,复习一下。学习二叉树的通用解题方法。

struct info{
        int depth;
        bool isBala;
        info():depth(0), isBala(true){};
        info(int d, bool b):depth(d), isBala(b){};
    };
    info Balance(TreeNode* node){
        if(node == NULL) return info();
        info left = Balance(node->left);
        info right = Balance(node->right);
        bool cur_isBala = abs(left.depth - right.depth) <= 1;
        cur_isBala = cur_isBala && left.isBala && right.isBala;
        int cur_depth = left.depth > right.depth ? left.depth + 1 : right.depth + 1;
        return info(cur_depth, cur_isBala);
    }
    bool isBalanced(TreeNode* root) {
        return Balance(root).isBala;
    }

;