首页 > 其他 > 详细

判断二叉树是否平衡

时间:2016-09-21 21:28:14      阅读:112      评论:0      收藏:0      [点我收藏+]

 

 

 

//                      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;
        
        
    }
};

  

判断二叉树是否平衡

原文:http://www.cnblogs.com/laiqun/p/5894071.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!