求二叉树中节点的最大距离

写一个程序求一棵二叉树中相距最远的两个节点之间的距离

 

struct Node { Node* pLeft; Node* pRight; int nMaxLeft; int nMaxRight; char chValue; }; int nMaxLen = 0; void FindMaxLen(Node* pRoot) { if (pRoot==NULL) { return; } if (pRoot->pLeft == NULL) { pRoot->nMaxLeft = 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->pRight->nMaxRight) { nTempMax = pRoot->pLeft->nMaxLeft; } else { nTempMax = pRoot->pRight->nMaxRight; } pRoot->nMaxLeft = nTempMax + 1; } if (pRoot->pRight!=NULL) { int nTempMax = 0; if (pRoot->pLeft->nMaxLeft > pRoot->pRight->nMaxRight) { nTempMax = pRoot->pLeft->nMaxLeft; } else { nTempMax = pRoot->pRight->nMaxRight; } pRoot->nMaxRight = nTempMax + 1; } if (pRoot->nMaxLeft + pRoot->nMaxRight > nMaxLen) { nMaxLen = pRoot->nMaxLeft + pRoot->nMaxRight; } } 

你可能感兴趣的:(求二叉树中节点的最大距离)