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

struct NODE { NODE* pLeft; NODE* pRight; int nMaxLeft; //左子树中的最长距离 int nMaxRight; //右子树中的最长的距离 char chValue; //该节点的值 }; int nMaxlen = 0; void FindMaxlen(NODE* pRoot) { if(NULL == pRoot) return; //左子树为空,那么该节点的左边的最长距离为0 if(NULL == pRoot->pLeft) pRoot->nMaxLeft = 0; //右子树为空,那么该节点的右边的最常的距离为0 if(NULL == pRoot->pRight) pRoot->nMaxRight = 0; //分别递归寻找左右子树的最长距离 if(NULL != pRoot->pLeft) FindMaxlen(pRoot->pLeft); if(NULL != pRoot->pRight) FindMaxlen(pRoot->pRight); //计算左边子树最长节点距离 if(NULL != pRoot->pLeft) { int nTempMax = 0; if(pRoot->pLeft->nMaxLeft > pRoot->pLeft->nMaxRight) nTempMax = pRoot->pLeft->nMaxLeft; else nTempMax = pRoot->pLeft->nMaxRight; pRoot->nMaxLeft = nTempMax+1; } //计算右子树的最长节点距离 if(NULL != pRoot->pRight) { 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; }

你可能感兴趣的:(struct,null)