平衡二叉树
递归处理左右子树
如果子树平衡,则返回其高度,否则返回0
/**
* 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:
int dfs(TreeNode* root)
{
if (!root->left && !root->right) return 1;
int ld = 0, rd = 0;
if (root->left)
{
ld = dfs(root->left);
if (ld == 0) return 0; // 如果发现这棵子树不平衡,则返回0
}
if (root->right)
{
rd = dfs(root->right);
if (rd == 0) return 0;
}
if (abs(ld - rd) > 1) return 0;
return max(ld, rd) + 1;
}
bool isBalanced(TreeNode* root) {
if (!root) return true;
if (!dfs(root)) return false;
return true;
}
};