您的位置:首页 > 其它

判断二叉树是否平衡

2016-09-21 20:42 211 查看
//                      1
//              2             3
//        4                         5
//
//

class Solution {
public:
int maxDepth(TreeNode* root){
if(root==NULL)
return 0;

return 1+max(maxDepth(root->left),maxDepth(root->right));
}
bool danbian(TreeNode *root)
{
if(root==NULL)
return 1;
if(root->left!=NULL && root->right!=NULL)
return 0;
if(root->left==NULL)
;//danbian(root->right);
if(root->right==NULL)
;//danbian(root->left);
return 1;
}
int minDepth(TreeNode* root){

if(root==NULL)
return 0;

if(root->left == NULL) return minDepth(root->right) + 1;
if(root->right == NULL) return minDepth(root->left) + 1;

int leftDepth = minDepth(root->left);
int rightDepth = minDepth(root->right);
return leftDepth < rightDepth ? (leftDepth + 1) : (rightDepth + 1);
}
bool IsBalanced_Solution(TreeNode* pRoot) {
int max=maxDepth(pRoot);
int min=minDepth(pRoot);
if(danbian(pRoot))
min=1;
if(max-min>1)
return 0;
return 1;

}
};


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: