题意:判断二叉树是否为平衡树。左右子树高度差最多为1的树是平衡树。
分析:借助求树高判断是否为平衡树。
/** * 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: bool ans = true; int maxDepth(TreeNode* root){ if(root == NULL) return 0; int l = maxDepth(root -> left); int r = maxDepth(root -> right); if(abs(l - r) > 1) ans = false; return max(l, r) + 1; } bool isBalanced(TreeNode* root) { maxDepth(root); return ans; } };