问题描述
代码
/**
* 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 len(TreeNode *a)
{
if(a==NULL) return 0;
if(a->left==NULL &&a->right==NULL) return 1;
return max(len(a->left),len(a->right))+1;
}
bool isBalanced(TreeNode* root) {
if(root==NULL) return true;
if(len(root->left)-len(root->right)>1||len(root->left)-len(root->right)<-1) return false;
return isBalanced(root->left)&&isBalanced(root->right);
}
};
采用双递归,一处递归用来求树的深度,,另一处来解决平衡二叉树问题