给定一个二叉树,判断它是否是
平衡二叉树
示例 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;}