(三)剑指offer38 平衡二叉树的判断

思路:根据定义判断  dis=(left-right)《=1是否成立;

方法1:求出每个节点的高度;然后再判断,递归判断左右子树是否是平衡二叉树(重复遍历了节点)

方法2:把求根节点的高度的时候 记录下求得的每一个结点的高度;然后判断左右子树是不是平衡的二叉树;再判断root是不是

代码:

class Solution {
public:
    //method1
    /*int depth(TreeNode *root)
    {
        if(!root)return 0;
        return 1+max(depth(root->left),depth(root->right));
    }
    bool IsBalanced_Solution(TreeNode* root)
    {
        if(!root)return true;
        int left=depth(root->left);
        int right=depth(root->right);
        int dis=abs(left-right);
        if(dis<=1)
            return IsBalanced_Solution(root->left)&&IsBalanced_Solution(root->right);
        return false;
    }
    */
    /*
    int depth(TreeNode *root,bool &res)
    {
        if(!root)return 0;
        //int left=0;
        //int right=0;
        int left=depth(root->left,res);
        int right=depth(root->right,res);
        int dis=left-right;
        if(dis>1||dis<-1)
            res=false;
        return 1+max(left,right);
    }
    bool IsBalanced_Solution(TreeNode* root)
    {
        if(!root)return true;
        bool res=true;
        depth(root,res);
        return res;
    }
    */
    bool helper(TreeNode *root,int &dep)
    {
        if(!root)return true;
        int left=0;
        int right=0;
        if(helper(root->left,left)&&helper(root->right,right))
        {
            int dis=left-right;
            dep=1+max(left,right);
            if(dis<-1||dis>1)
                return false;
            return true;
        }
        return false;
    }
    bool IsBalanced_Solution(TreeNode* root)
    {
        if(!root)return true;
        int dep=0;
        return helper(root,dep);
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值