編程之美3.8 求二叉樹中節點的最大距離

11. 求二叉樹中節點的最大距離
如果我們把二叉樹看成一個圖,父子節點之間的連線看成是雙向的,我們姑且定義"距離"爲兩節點之間邊的個數。

寫一個程序,求一棵二叉樹中相距最遠的兩個節點之間的距離。


分析: 對任意一個節點,以該節點爲根,假設這個根有k個孩子節點,那麼相距最遠的兩個節點U和V之間的路徑與這個根節點的關係有兩種情況。
 1.若路徑經過根Root,則U和V是屬於不同的子樹的,且它們都是該子樹中到根節點最遠的節點,否則跟它們的距離最遠相矛盾。
2.若路徑不經過Root,那它們一定同屬於根的左子樹或右子樹,並且它們也是該子樹中相距最遠的兩個頂點。
因此,問題就可以轉化爲在子樹上的解,從而能夠利用動態規劃來解決。


#include <iostream>
using namespace std;
struct NODE
{
	 NODE* pLeft;        // 左子樹
	 NODE* pRight;       // 右子樹
	 int nMaxLeft;       // 左子樹中的最長距離
	 int nMaxRight;      // 右子樹中的最長距離
	 char chValue;       // 該節點的值
	 NODE(char c = '\0'):pLeft(NULL), pRight(NULL), nMaxLeft(0), nMaxRight(0), chValue(c){}
};
int nMaxLen = 0;

// 尋找樹中最長的兩段距離
void FindMaxLen(NODE* pRoot)
{
	 // 遍歷到葉子節點,返回
	 if(pRoot == NULL)
	 {
		return;
	 }
	 // 如果左子樹爲空,那麼該節點的左邊最長距離爲0
	 if(pRoot -> pLeft == NULL)
	 {  
		pRoot -> nMaxLeft = 0;
	 }
	 // 如果右子樹爲空,那麼該節點的右邊最長距離爲0
	 if(pRoot -> pRight == NULL)
	 {
		pRoot -> nMaxRight = 0;
	 }
	 cout << pRoot->chValue << endl;
	 // 如果左子樹不爲空,遞歸尋找左子樹最長距離
	 if(pRoot -> pLeft != NULL)
	 {
		FindMaxLen(pRoot -> pLeft);
	 }
	 // 如果右子樹不爲空,遞歸尋找右子樹最長距離
	 if(pRoot -> pRight != NULL)
	 {
		FindMaxLen(pRoot -> pRight);
	 }
	 // 計算左子樹最長節點距離
	 if(pRoot -> pLeft != NULL)
	 {
		  int nTempMax = 0;
		  if(pRoot -> pLeft -> nMaxLeft > pRoot -> pLeft -> nMaxRight)
		  {
				nTempMax = pRoot -> pLeft -> nMaxLeft;
		  }	
		  else
		  {
				nTempMax = pRoot -> pLeft -> nMaxRight;
		  }
		  pRoot -> nMaxLeft = nTempMax + 1;
		  cout << "pRoot-left-MaxRight " << pRoot->chValue << " " <<  pRoot -> nMaxRight << endl;
	 }

	 // 計算右子樹最長節點距離
	 if(pRoot -> pRight != NULL)
	 {
		  int nTempMax = 0;
		  if(pRoot -> pRight -> nMaxLeft > pRoot -> pRight -> nMaxRight)
		  {
			  nTempMax = pRoot -> pRight -> nMaxLeft;
		  }
		  else
		  {
			  nTempMax = pRoot -> pRight -> nMaxRight;
		  }
		  pRoot -> nMaxRight = nTempMax + 1;
		  cout << "pRoot-right-MaxRight " << pRoot->chValue << " " <<  pRoot -> nMaxRight << endl;
	 }
	 // 更新最長距離
	 if(pRoot -> nMaxLeft + pRoot -> nMaxRight > nMaxLen)
	 {
		 nMaxLen = pRoot -> nMaxLeft + pRoot -> nMaxRight;
		 cout << "nMaxLen " << pRoot->chValue << " " <<  nMaxLen << endl;
	}
}
int main()
{
	 NODE node[9];
	 /*
	 for (char i = '1'; i <= '9'; ++i)
	 {
		node[i-'1'].chValue = i;
	 }
	 node[0].pLeft = &node[1];
	 node[0].pRight = &node[8];
	 node[1].pLeft = &node[2];
	 node[1].pRight = &node[5];
	 node[2].pLeft = &node[3];
	 node[3].pLeft = &node[4];
	 node[5].pRight = &node[6];
	 node[6].pRight = &node[7];
	 */
	 for (char i = '1'; i <= '9'; ++i)
	 {
		node[i-'1'].chValue = i;
	 }
	 node[0].pLeft = &node[1];
	 node[0].pRight = &node[2];
	 node[1].pLeft = &node[3];
	 node[1].pRight = &node[4];
	 node[2].pLeft = &node[5];
	 node[2].pRight = &node[6];
	 node[3].pLeft = &node[7];
	 node[5].pRight = &node[8];
	 FindMaxLen(&node[0]);
	 cout << "MaxLengthFin " << nMaxLen << endl;
	 system("pause");
	 return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章