110 Balanced Binary Tree

方法一:(笨办法,把每一个结点的两个子树深度作差,判断是否小于1,进行深度优先遍历判断,貌似复杂度比较高)

class Solution {
public:
    int getDepth(TreeNode *root){
        if(root==NULL)
            return 0;
        if(root->left==NULL&&root->right==NULL)
            return 1;
        int l=0, r=0;
        if(root->left!=NULL)
            l=1+getDepth(root->left);
        if(root->right!=NULL)
            r=1+getDepth(root->right);
        return max(l,r);
            
    }
    
    bool isBalanced(TreeNode *root) {
        if(root==NULL)
            return true;
        return abs(getDepth(root->left)-getDepth(root->right))<=1&&isBalanced(root->left)&&isBalanced(root->right);
    };
};


方法二:(少嵌套一个dfs,每次递归计算深度的时候就进行差值比较,一旦不满足小于等于1就标记一个特殊值-1, 比较奇怪的是这个方法跑出来时间比上一个方法还要长...)
class Solution {
public:
    struct TreeNode {
        int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    };
    
    int getDepth(TreeNode *root){
        if(root==NULL)
            return 0;
        if(root->left==NULL&&root->right==NULL)
            return 1;
        int l=0, r=0;
        if(root->left!=NULL)
            l=getDepth(root->left);
        if(root->right!=NULL)
            r=getDepth(root->right);
        if(l==-1||r==-1||abs(l-r)>1)
            return -1;
        return max(l,r)+1;
    }
    
    bool isBalanced(TreeNode *root) {
        return getDepth(root)!=-1;
    };
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值