/* *1.編程之美上的解法。 */struct NODE{ NODE* pLeft; // 左子樹 NODE* pRight; // 右子樹 int nMaxLeft; // 左子樹中的最長距離 int nMaxRight; // 右子樹中的最長距離 char chValue; // 該節點的值};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; } // 如果左子樹不為空白,遞迴尋找左子樹最長距離 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; } // 計算右子樹最長節點距離 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; } // 更新最長距離 if(pRoot -> nMaxLeft + pRoot -> nMaxRight > nMaxLen) { nMaxLen = pRoot -> nMaxLeft + pRoot -> nMaxRight; }}
//其他解法2#include <stdio.h>#include <stdlib.h>#include <malloc.h>#define LEAF -1typedef struct BTreeNode{ BTreeNode* lchild; BTreeNode* rchild; int value;}BTreeNode,*Btree;BTreeNode* createTree(){ BTreeNode* T; int t; scanf("%d",&t); if(t == LEAF){ T = NULL; }else{ T = (BTreeNode *) malloc(sizeof(BTreeNode)); T->value = t; T->lchild = createTree(); T->rchild = createTree(); } return T;}int max(int a,int b){return a > b ? a : b;}int findMaxLen(BTreeNode* root,int &depth){ if(root == NULL){depth = 0;return 0;} int leftLen = 0,rightLen = 0,maxLeft = 0,maxRight = 0;if(root->lchild != NULL){maxLeft = findMaxLen(root->lchild,leftLen);}if(root->rchild != NULL){maxRight = findMaxLen(root->rchild,rightLen);}depth = max(leftLen,rightLen) + 1; return max(maxLeft,max(maxRight,leftLen + rightLen));}main(){ BTreeNode * root; root = createTree();int depth = 0,maxLen = 0; maxLen = findMaxLen(root,depth); printf("%d \n",maxLen); system("pause"); return 0;}
//引用:http://www.cnblogs.com/miloyip/archive/2010/02/25/binary_tree_distance.html//解法3using namespace std;struct NODE{NODE *pLeft;NODE *pRight;};struct RESULT{int nMaxDistance;int nMaxDepth;};RESULT GetMaximumDistance(NODE* root){if (!root){RESULT empty = { 0, -1 };// trick: nMaxDepth is -1 and then caller will plus 1 to balance it as zero.return empty;}RESULT lhs = GetMaximumDistance(root->pLeft);RESULT rhs = GetMaximumDistance(root->pRight);RESULT result;result.nMaxDepth = max(lhs.nMaxDepth + 1, rhs.nMaxDepth + 1);result.nMaxDistance = max(max(lhs.nMaxDistance, rhs.nMaxDistance), lhs.nMaxDepth + rhs.nMaxDepth + 2);return result;}