題目:如果我們把二叉樹看成一個圖,父子節點之間的連線看成是雙向的,我們姑且定義”距離”爲兩節點之間邊的個數。寫一個程序,求一棵二叉樹中相距最遠的兩個節點之間的距離.
例如:
10
/ \
5 12
/ \
4 7
這棵樹的話,最大距離爲3.分別路徑爲4,5,10,12共3條邊,7,5,10,12共3條邊,所以最大距離爲3.
遞歸的思想,分別考慮左右子樹的,從根節點開始.
代碼如下:
#include<iostream>
using namespace std;
struct BiTreeNode
{
int m_nValue;
BiTreeNode *m_pleft;
BiTreeNode *m_pright;
int m_nMaxLeft;
int m_nMaxRight;
};
int nMaxLen = 0;
void findMaxLen(BiTreeNode *pRoot);
void addBiTreeNode(BiTreeNode *&pCurrent, int value);
int main()
{
BiTreeNode *pRoot = NULL;
addBiTreeNode(pRoot, 10);
addBiTreeNode(pRoot, 5);
addBiTreeNode(pRoot, 4);
addBiTreeNode(pRoot, 7);
addBiTreeNode(pRoot, 12);
findMaxLen(pRoot);
cout<<nMaxLen<<endl;
return 0;
}
void findMaxLen(BiTreeNode *pRoot)
{
if(pRoot == NULL)
return ;
if(pRoot->m_pleft == NULL)
pRoot->m_nMaxLeft = 0;
if(pRoot->m_pright == NULL)
pRoot->m_nMaxRight = 0;
if(pRoot->m_pleft != NULL)
findMaxLen(pRoot->m_pleft);
if(pRoot->m_pright != NULL)
findMaxLen(pRoot->m_pright);
if(pRoot->m_pleft != NULL)
{
int nTempMax = 0;
if(pRoot->m_pleft->m_nMaxLeft > pRoot->m_pleft->m_nMaxRight)
nTempMax = pRoot->m_pleft->m_nMaxLeft;
else
nTempMax = pRoot->m_pleft->m_nMaxRight;
pRoot->m_nMaxLeft = nTempMax + 1;
}
if(pRoot->m_pright != NULL)
{
int nTempMax = 0;
if(pRoot->m_pright->m_nMaxLeft > pRoot->m_pright->m_nMaxRight)
nTempMax = pRoot->m_pright->m_nMaxLeft;
else
nTempMax = pRoot->m_pright->m_nMaxRight;
pRoot->m_nMaxRight = nTempMax + 1;
}
if(pRoot->m_nMaxLeft + pRoot->m_nMaxRight > nMaxLen)
nMaxLen = pRoot->m_nMaxLeft + pRoot->m_nMaxRight;
}
void addBiTreeNode(BiTreeNode *&pCurrent, int value)
{
if(pCurrent == NULL)
{
BiTreeNode *pBiTree = new BiTreeNode();
pBiTree->m_nValue = value;
pBiTree->m_pleft = NULL;
pBiTree->m_pright = NULL;
pCurrent = pBiTree;
}
else
{
if((pCurrent->m_nValue) > value)
addBiTreeNode(pCurrent->m_pleft, value);
else if((pCurrent->m_nValue) < value)
addBiTreeNode(pCurrent->m_pright, value);
}
}