递归检查每个节点其左右子树最大深度差不超过1即可。
-
/**
-
* Definition for binary tree
-
* struct TreeNode {
-
* int val;
-
* TreeNode *left;
-
* TreeNode *right;
-
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
-
* };
-
*/
-
class Solution {
-
public:
-
void depth(TreeNode *node, int dep, int *maxdep)
-
{
-
if(NULL==node) {if(*maxdep<dep) *maxdep=dep; return;}
-
dep++;
-
depth(node->left, dep, maxdep);
-
depth(node->right, dep, maxdep);
-
}
-
bool isBalanced(TreeNode *root) {
-
if(NULL==root) return true;
-
int leftdep=0;
-
int rightdep=0;
-
depth(root->left,0,&leftdep);
-
depth(root->right,0,&rightdep);
-
if(abs(leftdep-rightdep)>1) return false;
-
return isBalanced(root->left)&&isBalanced(root->right);
-
}
-
};
阅读(102) | 评论(0) | 转发(0) |