题目:
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;
}