剑指offer-55

二叉树的深度

55.1 求一二叉树的深度

解法一:用递归法遍历树的每一条路径,用一引用变量记录所下的层次数,每次到一个叶节点进行一次比较

解法二:用一个队列进行广度优先遍历,直至叶节点,位置一个全局的层数

解法三:因为单纯是计算树的深度,一棵树某一点的深度,无非是左子树+1或右子树+1

解法一
void TreeDepthCore(const BinaryTreeNode* pRoot,int tempdeep,int& maxDeepth)//diy
{
	if (pRoot->m_pLeft==nullptr && pRoot->m_pRight==nullptr)
	{
		maxDeepth = tempdeep > maxDeepth ? tempdeep : maxDeepth;
		return;
	}
	if (pRoot->m_pLeft != nullptr)
		TreeDepthCore(pRoot->m_pLeft, tempdeep + 1, maxDeepth);
	if (pRoot->m_pRight != nullptr)
		TreeDepthCore(pRoot->m_pRight, tempdeep + 1, maxDeepth);
}

int TreeDepth(const BinaryTreeNode* pRoot)//diy 遍历所有路径
{
	if (pRoot == nullptr) return 0;
	int deepths = 0;
	TreeDepthCore(pRoot,1,deepths);
	return deepths;
}

解法二:
int TreeDepth2(const BinaryTreeNode* pRoot)//diy 广度优先
{
	if (pRoot == nullptr) return 0;
	int deepths = 0;
	int layerCnt = 1;
	std::queue<const BinaryTreeNode*> mQueue;
	mQueue.push(pRoot);
	while (mQueue.size()>0)
	{		
		if (layerCnt > 0)
			deepths++;
		int tempCnt = 0;
		while (layerCnt>0)
		{
			const BinaryTreeNode* pTemp = mQueue.front();
			mQueue.pop();
			if (pTemp->m_pLeft!=nullptr)
			{
				tempCnt++;
				mQueue.push(pTemp->m_pLeft);
			}
			if (pTemp->m_pRight!=nullptr)
			{
				tempCnt++;
				mQueue.push(pTemp->m_pRight);
			}
			layerCnt--;
		}
		layerCnt = tempCnt;
	}
	return deepths;
}

解法三:
int TreeDepth1(const BinaryTreeNode* pRoot)//diy
{
	if (pRoot == nullptr) return 0;
	int left = TreeDepth1(pRoot->m_pLeft);
	int right = TreeDepth1(pRoot->m_pRight);
	return left > right ? (left+1) : (right+1);
}

55.2平衡二叉树,判断一棵树是否是平衡二叉树,只要任意节点的左右深度差超过1,就不是平衡二叉树

解法一:通过递归遍历任何一个节点的左右子树,如果左右子树高度差大于1,返回-1,否则返回子树的高度

int IsBalanced_Solution3_core(const BinaryTreeNode* pRoot)
{
	if (pRoot == nullptr) return 0;
	if (pRoot->m_pLeft == nullptr && pRoot->m_pRight == nullptr) return 1;

	int left = IsBalanced_Solution3_core(pRoot->m_pLeft);
	int right = IsBalanced_Solution3_core(pRoot->m_pRight);
	if (left == -1 || right == -1) return -1;
	if (left - right > 1 || right - left > 1) return -1;

	return left > right ? left+1 : right+1;
}

bool IsBalanced_Solution3(const BinaryTreeNode* pRoot)
{
	if (pRoot == nullptr) return true;
	if (IsBalanced_Solution3_core(pRoot) == -1) return false;
	else
		return true;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值