【2】输入一颗二叉树判断是不是平衡二叉树

题目:输入一颗二叉树的根结点,判断该二叉树是不是平衡二叉树。平衡二叉树是满足所有结点的左右子树的高度差不超过1的二叉树


方案一:遍历数组的每一个结点,对每一个结点求它的左右子树的高度并进行判断。时间复杂度大于O(n),小于O(n^2)效率较低,因为有很多点需要重复访问。

//二叉树的结点
struct BinaryTreeNode{
     int m_value;
     BinaryTreeNode *m_lson;
     BinaryTreeNode *m_rson;
};

//求二叉树的深度
int GetDepth(BinaryTreeNode *root){
	if(root == NULL){
	   return 0;
	}
	int lsonDepth = GetDepth(root->m_lson);
	int rsonDepth = GetDepth(root->m_rson);
	return lsonDepth < rsonDepth ? (rsonDepth+1) : (lsonDepth+1);
}

//方案一对每个结点进行判断
bool IsBalanced(BinaryTreeNode *root){
	if(root == NULL){
	    return true;
	}
	int lsonDepth = GetDepth(root->m_lson);
	int rsonDepth = GetDepth(root->m_rson);
	int dis = lsonDepth-rsonDepth;
	if((dis <= 1) && (dis >= -1)){
		return IsBalanced(root->m_lson) && IsBalanced(root->m_rson);
	}
	else{
	    return false;
	}
} 


方案二:利用二叉树的后序遍历,对于先访问左右子树,然后对每个根结点进行判断,传入一个高度的参数即可。时间复杂度为O(n)。

//二叉树的结点
struct BinaryTreeNode{
     int m_value;
     BinaryTreeNode *m_lson;
     BinaryTreeNode *m_rson;
};

//后序遍历判断是不是平衡二叉树
bool IsBalanced(BinaryTreeNode *root, int *depth){
	if(root == NULL){
	    *depth = 0;
	    return true;
	}
	int lsonDepth = 0;
	int rsonDepth = 0;
	if(IsBalanced(root->m_lson, &lsonDepth) 
		&& IsBalanced(root->m_rson, &rsonDepth)){
	    int dis = lsonDepth-rsonDepth;
		if((dis >= -1) && (dis <= 1)){
		    *depth = 1+(lsonDepth < rsonDepth ? rsonDepth : lsonDepth);
		    return true;
		}
		else{
		    return false;
		}
	}
	else{
	    return false;
	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值