剑指Offer之 - 二叉树的深度

题目:

1、求二叉树的最大深度和最小深度。

2、判断一棵二叉树是不是平衡二叉树。

代码:

#include <iostream>
using namespace std;

struct BinaryTreeNode
{
	int m_nValue;
	BinaryTreeNode *m_pLeft;
	BinaryTreeNode *m_pRight;
	BinaryTreeNode(){}
	BinaryTreeNode(int value):m_nValue(value),m_pLeft(NULL),m_pRight(NULL){}
};

//功能:求二叉树的最大深度和最小深度

int TreeDepthMax(BinaryTreeNode *pRoot)
{
	if(pRoot == NULL)
		return 0;
	int nLeft = TreeDepthMax(pRoot->m_pLeft);
	int nRight = TreeDepthMax(pRoot->m_pRight);
	return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}

int TreeDepthMin(BinaryTreeNode *pRoot)
{
	if(pRoot == NULL)
		return 0;
	if(pRoot->m_pLeft == NULL || pRoot->m_pRight == NULL)
		return 1;
	int nLeft = TreeDepthMin(pRoot->m_pLeft);
	int nRight = TreeDepthMin(pRoot->m_pRight);
	if(!pRoot->m_pLeft)	//左为空,返回右+1
		return nRight + 1;
	if(!pRoot->m_pRight)	//右为空,返回左+1
		return nLeft + 1;
	return (nLeft > nRight) ? nRight + 1 : nLeft + 1;	//左右都不为空,返回小的+1
}


//功能:判断一棵树是不是平衡二叉树,即任意结点的左右子树的深度相差不超过1
//思路1:求出每个结点的左右子树深度,然后再比较,效率较低
bool IsBalanced(BinaryTreeNode *pRoot)
{
	if(pRoot == NULL)
		return true;
	int left = TreeDepthMax(pRoot->m_pLeft);
	int right = TreeDepthMax(pRoot->m_pRight);
	int diff = left - right;
	if(diff > 1 || diff < -1)
		return false;
	return IsBalanced(pRoot->m_pLeft) && IsBalanced(pRoot->m_pRight);
}

//思路2:记录下每个结点的深度,并作为形参传入
//用从下至上遍历的方式遍历二叉树的每一个结点,在遍历到一个结点之前我们已经遍历了它的左右子树。只要在遍历每个结点的时候记录它的深度
//我们就可以一边遍历一边判断每个结点是不是平衡的。
bool IsBalancedTree(BinaryTreeNode *pRoot , int *depth)
{
	if(pRoot == NULL)
	{
		*depth = 0;
		return true;
	}
	int left = 0 , right = 0;
	if(IsBalancedTree(pRoot->m_pLeft , &left) && IsBalancedTree(pRoot->m_pRight , &right))
	{
		int diff = left - right;
		if(diff <= 1 && diff >= -1)
		{
			*depth = 1 + (left > right ? left : right);
			return true;
		}
	}
	return false;
}
bool IsBalancedTree(BinaryTreeNode *pRoot)
{
	int depth = 0;
	bool result = IsBalancedTree(pRoot , &depth);
	return result;	
}

int main()
{
	BinaryTreeNode *p1 = new BinaryTreeNode(1);
	BinaryTreeNode *p2 = new BinaryTreeNode(2);
	BinaryTreeNode *p3 = new BinaryTreeNode(3);
	BinaryTreeNode *p4 = new BinaryTreeNode(4);
	BinaryTreeNode *p5 = new BinaryTreeNode(5);
	p1->m_pLeft = p2;
	p1->m_pRight = p3;
	p3->m_pRight = p4;
	p4->m_pRight = p5;
	int depth = TreeDepthMax(p1);
	int minDepth = TreeDepthMin(p1);
	cout<<depth<<endl;
	cout<<minDepth<<endl;
	cout<<IsBalancedTree(p1)<<endl;
	cout<<IsBalanced(p1)<<endl;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值