思想:
检查每个节点的左子树深度(ldeep)和右子树深度(rdeep)
如果相差超过1,则设置标志位
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Balance { public: int flag = 0; int dfs(TreeNode* root, int deepth) { if (root == NULL) { return deepth; } int ldeep = dfs(root->left, deepth + 1); int rdeep = dfs(root->right, deepth + 1); if (abs(ldeep - rdeep) > 1) { flag = 1; } return max(ldeep, rdeep); } bool isBalance(TreeNode* root) { dfs(root, 0); return flag == 0; } };