平衡二叉树(29)

题目

【输入一棵二叉树,判断该二叉树是否是平衡二叉树】


1、分析

  • 平衡二叉树:如果某二叉树中任意节点的左、右子树深度相差不超过1,那么它就是一颗平衡二叉树。
  • 可以使用递归的方式将每个节点的左右子树的深度进行遍历,再进行计算是否为平衡二叉树。

2、代码

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(pRoot==nullptr)
            return true;
        int left=TreeDepth(pRoot->left);
        int right=TreeDepth(pRoot->right);
        int dis=abs(left-right);
        if(dis<=1)
            return true;
        else
            return false;
        
        return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
    }
    int TreeDepth(TreeNode *pRoot)
    {
        if(pRoot==nullptr)
            return 0;
        int leftDep=TreeDepth(pRoot->left);
        int rightDep=TreeDepth(pRoot->right);
        return (leftDep>rightDep)?(leftDep+1):(rightDep+1);
    }
    
};

改进的方法:
1、分析
由于之前的方法会重复的遍历一些节点从而影响了程序的性能,所以改进的方法是每个节点只遍历一次,在遍历的同时将其结果记录下来,方便下次直接使用,而无需再次遍历。
对于二叉树的深度,当使用后序遍历时,可以先遍历其子树,将其深度记录下来,这样下次可以直接使用。
2、代码

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        int depth=0; //depth用来记录遍历过的子树的深度值,避免重复遍历
        return IsBalanced(pRoot,&depth);
    }
    bool IsBalanced(TreeNode *pRoot, int *pDepth)
    {
        if(pRoot==nullptr)
        {
            *pDepth=0;
            return true;
        }
        int leftDep,rightDep;
        if(IsBalanced(pRoot->left,&leftDep) && IsBalanced(pRoot->right,&rightDep))
        {
            int dis=abs(leftDep-rightDep);
            if(dis<=1)
            {
                *pDepth=1+(leftDep>rightDep?leftDep:rightDep);
                return true;
            }
        }
        return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值