《编程之美》 3.8 求二叉树节点中的最大距离
问题:如果把二叉树看成一个图,并且父子结点之间的连线看成是双向的,姑且定义“距离”为两个结点之间边的个数,求一棵二叉树中相距最远的两个结点之间的距离。
解法一:详见《编程之美》3.8以及代码。
代码一:
typedef struct BinTreeNode
{
char data;
int nMaxLeft;
int nMaxRight;
BinTreeNode *lchild,*rchild;
};
/*------------------------------------------------------------------------*/
void FindMaxDist(BinTreeNode *pRoot)
{
if (pRoot == NULL) {
return;
}
if (pRoot->lchild == NULL) {
pRoot->nMaxLeft = 0;
}
if (pRoot->rchild == NULL) {
pRoot->nMaxRight = 0;
}
if (pRoot->lchild != NULL) {
FindMaxDist(pRoot->lchild);
}
if (pRoot->rchild != NULL) {
FindMaxDist(pRoot->rchild);
}
if (pRoot->lchild != NULL) {
int nTempMax = 0;
if (pRoot->lchild->nMaxLeft > pRoot->lchild->nMaxRight) {
nTempMax = pRoot->lchild->nMaxLeft;
}
else {
nTempMax = pRoot->lchild->nMaxRight;
}
pRoot->nMaxLeft = nTempMax + 1;
}
if (pRoot->rchild != NULL) {
int nTempMax = 0;
if (pRoot->rchild->nMaxLeft > pRoot->rchild->nMaxRight) {
nTempMax = pRoot->rchild->nMaxLeft;
}
else {
nTempMax = pRoot->rchild->nMaxRight;
}
pRoot->nMaxRight = nTempMax + 1;
}
if (pRoot->nMaxLeft + pRoot->nMaxRight > nMaxLen) {
nMaxLen = pRoot->nMaxLeft + pRoot->nMaxRight;
}
}
/*-------------------------------------------------------------------------*/
解法二:使用最基本的二叉树结点的定义,详见《 [编程之美]求二叉树中节点的最大距离》。
代码二:
#include <stdio.h>
#include <stdlib.h>
#include <stack>
using namespace std;
typedef struct BinTreeNode * BinTree;
typedef struct BinTreeNode
{
char data;
BinTreeNode *lchild,*rchild;
};
int MaxDistanceBetweenNodes(BinTreeNode *pRoot,int *pmax)
{
// return 0 if leaf node
if (pRoot->lchild == NULL && pRoot->rchild == NULL) {
return 0;
}
// depth of two sub-trees
int ldepth = 0;
int rdepth = 0;
if (pRoot->lchild != NULL) {
ldepth = 1 + MaxDistanceBetweenNodes(pRoot->lchild,pmax);
}
if (pRoot->rchild != NULL) {
rdepth = 1 + MaxDistanceBetweenNodes(pRoot->rchild,pmax);
}
if (ldepth + rdepth > *pmax) {
*pmax = ldepth + rdepth;
}
return ldepth > rdepth ? ldepth : rdepth;
}
int MaxDistanceInBinTree(BinTreeNode *pRoot,int *pmax)
{
if (pRoot == NULL || pmax == NULL) {
return -1;
}
*pmax = 0;
return MaxDistanceBetweenNodes(pRoot,pmax);
}
void buildBinTree(BinTree *T,char *str)
{
stack<BinTree> s;
*T = NULL;
BinTree p,t;
p = t = NULL;
int i,k;
i = 0;
while(str[i])
{
switch(str[i]){
case '(': s.push(p); k = 1; break;
case ')': t = s.top(); s.pop(); break;
case ',': k = 2; break;
default:
p = new BinTreeNode;
p->data = str[i];
p->lchild = p->rchild = NULL;
if (*T == NULL){
*T = p;
}
else if (k == 1){
t = s.top();
t->lchild = p;
}
else {
t = s.top();
t->rchild = p;
}
}
i++;
}
}
int main()
{
BinTree T;
char *t = "A(B(C,D),E(F,))";
buildBinTree(&T,t);
int *pmax = (int *)malloc(sizeof(int));
printf("Max Distance : %d %d.\n",*pmax,MaxDistanceInBinTree(T,pmax));
free(pmax);
}
测试输出:
Max Distance : 4 2.
REF:
1,《编程之美》 3.8 求二叉树中结点的最大距离
2,http://blog.csdn.net/lalor/article/details/7626678