平衡二叉树

题目描述:

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

思路:(后续遍历)

使用深度优先搜索的后续遍历的的方法,因为后续遍历的遍历顺序是左右根的访问顺序,所以对于每个节点,首先判断子树是否是平衡二叉树,如果子树是平衡二叉树,记录此时该子树的深度(用于与其他子树后续其他的判断),如果不是则整个二叉树就不是平衡二叉树,下面使用递归的方式遍历。

代码:

class solution
{
	public:
		bool whetherBalanced(TreeNode* root)
		{
			int depth=0;
			if(root)
				return isBalanced(root,&depth)
			return false;
		}
		
		bool isBalanced(TreeNode* p,int *depth)
		{
			if(!p)
				return true;
			int left=0;
			int right=0;
			if(isBalanced(p->left,&left)&&isBalanced(p->right,&right))
			{
				int diff=left-right;
				if(diff>-1&&diff<1)
				{
					*depth=(left>right)?left+1:right+1;
					return true;
				}
			}
			return false;
		}
}
class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        
            if(!pRoot)
                return true;
                    return isBalanced(pRoot);
    }
    
    bool isBalanced(TreeNode* pRoot)
    {
        
        int left=depth(pRoot->left);
        int right=depth(pRoot->right);
        if(left-right>1||left-right<-1)
            return false;
        else
            return true;
        return isBalanced(pRoot->left)&&isBalanced(pRoot->right);
    }
    
    int depth(TreeNode* pRoot)
    {
        if(!pRoot)
            return 0;
        int left=depth(pRoot->left);
        int right=depth(pRoot->right);
        return left>right?left+1:right+1;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值