(本博客旨在个人总结回顾)
题目描述:
输入一颗二叉树的根结点,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
二叉树的结点定义如下:
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
}
源码:
#include "stdafx.h"
#include<iostream>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
BinaryTreeNode(int nValue = 0, BinaryTreeNode* pLeft = NULL, BinaryTreeNode* pRight = NULL)
: m_nValue(m_nValue)
, m_pLeft(pLeft)
, m_pRight(pRight)
{
}
};
/*
* @name TreeDepth
* @brief 二叉树的深度
* @param [in] BinaryTreeNode * pRoot
* @return int
*/
int TreeDepth(BinaryTreeNode* pRoot)
{
if (NULL == pRoot)
{
return 0;
}
int left = TreeDepth(pRoot->m_pLeft);
int right = TreeDepth(pRoot->m_pRight);
return left > right ? left + 1 : right + 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
BinaryTreeNode* pRoot = new BinaryTreeNode(1);
BinaryTreeNode* pTmp = new BinaryTreeNode(7);
pTmp = new BinaryTreeNode(5, pTmp);
pTmp = new BinaryTreeNode(2, new BinaryTreeNode(4), pTmp);
pRoot->m_pLeft = pTmp;
pTmp = new BinaryTreeNode(6);
pTmp = new BinaryTreeNode(3, NULL, pTmp);
pRoot->m_pRight = pTmp;
cout << TreeDepth(pRoot) << endl;
system("pause");
return 0;
}
运行结果:
题目二:
输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树的任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。例如。图6.1中的二叉树就是一棵平衡二叉树。
源码:
#include "stdafx.h"
#include<iostream>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
BinaryTreeNode(int nValue, BinaryTreeNode* pLeft = NULL, BinaryTreeNode* pRight = NULL)
: m_nValue(nValue)
, m_pLeft(pLeft)
, m_pRight(pRight)
{
}
};
/*
* @name IsBalanceTree
* @brief 判断是否为平衡二叉树(递归)
* @param [in] BinaryTreeNode * pRoot
* @param [in] int & depth
* @return bool
*/
bool IsBalanceTree(BinaryTreeNode* pRoot, int& depth)
{
if (NULL == pRoot)
{
depth = 0;
return true;
}
int left;
int right;
if (IsBalanceTree(pRoot->m_pLeft, left)
&& IsBalanceTree(pRoot->m_pRight, right))
{
int diff = left - right;
if (diff <= 1 && diff >= -1)
{
depth = (left > right? left+1: right+1);
return true;
}
}
return false;
}
/*
* @name IsBalanceTree
* @brief 判断是否为平衡二叉树
* @param [in] BinaryTreeNode * pRoot
* @return bool
*/
bool IsBalanceTree(BinaryTreeNode* pRoot)
{
int depth = 0;
return IsBalanceTree(pRoot, depth);
}
int _tmain(int argc, _TCHAR* argv[])
{
BinaryTreeNode* pRoot = new BinaryTreeNode(1);
BinaryTreeNode* pTmp = new BinaryTreeNode(7);
pTmp = new BinaryTreeNode(5, pTmp);
pTmp = new BinaryTreeNode(2, new BinaryTreeNode(4), pTmp);
pRoot->m_pLeft = pTmp;
pTmp = new BinaryTreeNode(6);
pTmp = new BinaryTreeNode(3, NULL, pTmp);
pRoot->m_pRight = pTmp;
cout << "Is balance binary tree:" << (IsBalanceTree(pRoot) ? "true" : "false") << endl;
cout << "Is balance binary tree:" << (IsBalanceTree(NULL) ? "true" : "false") << endl;
system("pause");
return 0;
}
运行结果: